正在努力从VB.net访问SQL Server存储过程:
DECLARE @R INT
DECLARE @trm VARCHAR(255)
SET @trm = 'PartNumber'
EXECUTE @R = [dbo].[usp_CannedGlobalSearch] @trm
此SQL语句在SQL Server Management Studio中返回12列。效果很好。
Dim StoredConn As OdbcConnection = New OdbcConnection(SQLRdrConnectString)
Dim StoredCommand As New OdbcCommand
("CALL usp_CannedGlobalSearch (?)", StoredConn)
StoredCommand.CommandType = CommandType.StoredProcedure
StoredCommand.CommandText = "{? = CALL usp_CannedGlobalSearch(?)}"
StoredCommand.Parameters.Add("@RC", OdbcType.Int) 'this is the result
StoredCommand.Parameters.Add("@trm", OdbcType.VarChar) 'sending a search string
StoredCommand.Parameters("@term").Value = "PartNumber"
StoredConn.Open()
Dim TestInt As Integer = StoredCommand.ExecuteNonQuery()
运行时结果:
错误[HY105] [Microsoft] [ODBC SQL Server驱动程序]无效的参数类型。
答案 0 :(得分:0)
以下是使用显示的参数从VB.NET调用SQL Server中的存储过程的方法:
Dim testInt As Integer = -1
Using conn As New SqlConnection(SQLRdrConnectString)
Using cmd As New SqlCommand("usp_CannedGlobalSearch", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter With {
.ParameterName = "@trm",
.SqlDbType = SqlDbType.VarChar,
.Size = 255,
.Value = "PartNumber"})
conn.Open()
Dim res As Object = cmd.ExecuteScalar()
If res IsNot Nothing Then
testInt = Convert.ToInt32(res)
End If
End Using
End Using
带有Dim res As Object...
的部分将完全不考虑返回任何内容,甚至不返回NULL,并且testInt
的值将为-1,因此您可以进行检查。如果存储过程始终返回一个整数,则可以仅用一行替换它:
testInt = Convert.ToInt32(cmd.ExecuteScalar())