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