1.調用預存程序,但無傳回值
複製代碼 代碼如下:Private Function SqlProc1(ByVal ProcName As String) As Boolean
'定義資料連結部分省略, myConn為連結化物件 ProcName為預存程序名
Dim myCommand As New SqlClient.SqlCommand(ProcName, myConn)
With myCommand
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@CodeType", SqlDbType.VarChar, 20).Value = "年級編碼"
Try
.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
End Try
End Function
2.調用預存程序,返回普通值 複製代碼 代碼如下:Private Function SqlProc1(ByVal ProcName As String) As String
'定義資料連結部分省略, myConn為連結化物件
Dim myCommand As New SqlClient.SqlCommand(ProcName, myConn)
With myCommand
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@CodeType", SqlDbType.VarChar, 20).Value = "年級編碼"
.Parameters.Add("@NewCode", SqlDbType.VarChar, 20).Direction = ParameterDirection.Output
Try
.ExecuteNonQuery()
Return .Parameters(1).Value()
Catch ex As Exception
Return "無編碼產生"
End Try
End Function
3.調用預存程序,返回資料集
'VB.NET代碼 複製代碼 代碼如下:Private Function SqlProc2(ByVal ProcName As String, ByVal Param1 As String) As DataSet
'定義命令對象,並使用儲存過程
Dim myCommand As New SqlClient.SqlCommand
myCommand.CommandType = CommandType.StoredProcedure
myCommand.CommandText = ProcName
myCommand.Connection = myConn
'定義一個資料配接器,並設定參數
Dim myDapter As New SqlClient.SqlDataAdapter(myCommand)
myDapter.SelectCommand.Parameters.Add("@name", SqlDbType.VarChar, 20).Value = Param1
'定義一個資料集對象,並填充資料集
Dim myDataSet As New DataSet
Try
myDapter.Fill(myDataSet)
Catch ex As Exception
End Try
Return myDataSet
End Function
'預存程序代碼
Create Proc Test @name varchar(20) As
Select * From EC_Grade where cGradeName=@name
GO
***如果將預存程序修改部分內容,可以做為查詢使用
CREATE Proc Test
@name varchar(200)=''
--此處應該注意200為查詢條件的長度,可以根據實際情況而定;但不建議用於過長的查詢條件
As
Declare @sql1 varchar(8000)
if @name<>''
Select @sql1='Select * From EC_Grade where '+ @name
else
Select @sql1='Select * From EC_Grade'
exec(@sql1)
GO