VS中調用SQL SERVER預存程序

來源:互聯網
上載者:User





預存程序是經過編譯的,永久儲存在資料中的一組SQL語句,通過建立和使用預存程序可以提高程式的重用性和擴充性,為程式提供模組化的功能,還有利於對程式的維護和管理。下面就詳談一下,VB.NET如何調用SQL SERVER中的預存程序。

以上就是本人資料庫中的一張表—OnDutyInfo

建立預存程序

 

<span style="font-size:18px;">create procedure pro_OnDutyInfo    --預存程序名@teacherID char(11)   --參數名asselect * 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>

以上操作就是一個簡單的預存程序調用的操作,當然了大家可能會有問題,如果預存程序中的參數不止一個的話又該如何操作呢?如以下的預存程序

 我們看到其中會有很多傳入的參數,其實很簡單,不用擔心,只需改一下添加的方法而已。

<span style="font-size:18px;">ALTER procedure [dbo].[pro_AddOffInfo]@teacherId char(11),   --職工號@offTime time(0),  --下機時間@offDate date      --下機日期asupdate 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的區別。


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.