从VB.NET中的存储过程获取返回值

时间:2013-09-27 14:57:29

标签: sql-server vb.net

我有以下存储过程:

ALTER PROCEDURE [dbo].[BK_NUMBER]
    (@Category NUMERIC(38, 0)) 
WITH EXECUTE AS CALLER
AS
   DECLARE @RunningNumber Int
   DECLARE @min Int
   DECLARE @max Int
   DECLARE @newRunningNumber Int

   BEGIN

      SELECT @RunningNumber = RunningNumber
      FROM PARKMARKENNUMMER
      WHERE PARKMARKENTYP_ID = @Category

      UPDATE PARKMARKENNUMMER 
      SET RUNNINGNUMBER = @RunningNumber + 1
      WHERE PARKMARKENTYP_ID = @Category 

      SELECT @newRunningNumber = RunningNumber
      FROM PARKMARKENNUMMER 
      WHERE PARKMARKENTYP_ID = @Category 

      RETURN @newRunningNumber;
End;

我尝试使用此VB代码获取@newRunningNumber

 Dim sqlConnection As New SqlConnection(MSSQL_Helper.strConnectionBookit)
        Dim command As New SqlCommand("BK_NUMBER", sqlConnection)
        command.CommandType = CommandType.StoredProcedure
        command.Parameters.Add("@Category", SqlDbType.Int).Value = ID
        Dim returnParameter As SqlParameter = command.Parameters.Add("RetVal", SqlDbType.Int)
        returnParameter.Direction = ParameterDirection.ReturnValue
        sqlConnection.Open()
        command.ExecuteNonQuery()
        sqlConnection.Close()
        Dim returnValue As Integer = returnParameter.Value
        Return returnValue

但它总是返回“0”。我究竟做错了什么?

2 个答案:

答案 0 :(得分:5)

您实际上并没有返回值:

RETURN @newRunningNumber

但是,正如 Aaron Bertrand 所说,您应该将其设置为OUTPUT参数或SELECT将其设置为退出。

输出:

ALTER PROCEDURE [dbo].[BK_NUMBER]
(
    @Category NUMERIC(38, 0),
    @newRunningNumber INT
)

Dim newRunningNumber As SqlParameter("@newRunningNumber", SqlDbType.Int)
newRunningNumber.Direction = ParameterDirection.Output
// execute
Dim returnValue As Integer = newRunningNumber.Value

选择

SELECT @newRunningNumber AS NewRunningNumber

Dim returnValue As Integer = CType(command.ExecuteScalar(), Integer)

答案 1 :(得分:2)

虽然我同意其他帖子,但OUTPUT参数是要走的路,大多数人都没有意识到你可以在命令文本中加入多行。因为您可以,您可以将DBA所做的事情转换为您可以使用的内容,而无需更改存储过程。例如:

CMD.CommandText = "DECLARE @return_value int;EXEC   @return_value = [dbo].[BK_NUMBER] (@Category = " & ID & ";SELECT @return_value"
Dim Ret as int32 = CMD.ExecuteScalar

这只是您可以做的一个例子。您应该使用粗略的参数来避免注入并进行适当的错误处理等...