存储过程是经过编译的,永久保存在数据中的一组SQL语句,通过创建和使用存储过程能够提高程序的重用性和扩展性,为程序提供模块化的功能,还有利于对程序的维护和管理。以下就详谈一下,VB.NET怎样调用SQL SERVER中的存储过程。
以上就是本人数据库中的一张表—OnDutyInfo
创建存储过程
<span style="font-size:18px;">create procedure pro_OnDutyInfo --存储过程名
@teacherID char(11) --參数名
as
select * from OnDutyInfo where teacherId <a target=_blank href="mailto:=@teacherID">=@teacherID</a> </span>
(该存储过程运行查询教师值班记录操作)
要实现的功能是,查询用户的值班记录,在VS中的实现代码
<span style="font-size:18px;"> Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strCon As String '连接数据库字符串
Dim cn As SqlConnection
Dim cmd As New SqlCommand
Dim pt As SqlParameter
Dim rdr As SqlDataReader
strCon = "initial catalog=ChargeSystem;user id=sa;password=123456"
cn = New SqlConnection(strCon) '实例化连接对象
cmd.Connection = cn
cmd.CommandText = "pro_OnDutyInfo" '存储过程名字
cmd.CommandType = CommandType.StoredProcedure '表明连接的类型为存储过程
pt = New SqlParameter("@teacherID", "11090241032") '获取參数
cmd.Parameters.Add(pt) '这是add方法,该方法仅仅能加入一个參数
cn.Open()
rdr = cmd.ExecuteReader '读取操作
If (rdr.Read) Then '通过数据流的形式来读取数据
MessageBox.Show(rdr(0).ToString)
End If
End Sub</span>
以上操作就是一个简单的存储过程调用的操作,当然了大家可能会有问题,假设存储过程中的參数不止一个的话又该怎样操作呢?例如以下面的存储过程
我们看到当中会有非常多传入的參数,事实上非常easy,不用操心,仅仅需改一下加入的方法而已。
<span style="font-size:18px;">ALTER procedure [dbo].[pro_AddOffInfo]
@teacherId char(11), --职工号
@offTime time(0), --下机时间
@offDate date --下机日期
as
update OnDutyInfo set offTime=@offtime,offDate=@offdate where offtime is null and teacherid =@teacherId
--运行更新教师下机操作</span>
更改后的操作例如以下:
<span style="font-size:18px;">Dim paras As SqlParameter() = {New SqlParameter("@teacherId", En_OnDuty.teacherId), _
New SqlParameter("@offTime", En_OnDuty.offTime.ToString), _
New SqlParameter("@offDate", En_OnDuty.offDate.ToString)} '获取參数
cmd.Parameters.AddRange(paras) '注意这里换了一个方法</span>
以上就是实现VS调用SQL SERVER的小demo,也分析了ADD和ADDRanger的差别。