1

我有以下存储过程:

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;

我尝试@newRunningNumber使用这个 VB 代码:

 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”。我究竟做错了什么?

4

2 回答 2

6

您实际上并没有返回值:

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)
于 2013-09-27T15:28:57.610 回答
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

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

于 2013-09-27T17:53:48.150 回答