简体   繁体   English

如何获取存储过程的返回值

[英]How to get Return Value of a Stored Procedure

Probably an easy-to-answer question. 可能是一个容易回答的问题。 I have this procedure: 我有这个程序:

CREATE PROCEDURE [dbo].[AccountExists]
    @UserName nvarchar(16)
AS
IF EXISTS (SELECT Id FROM Account WHERE UserName=@UserName)
SELECT 1
ELSE SELECT 0 

When I have ADO.NET code that calls this procedure and does this: 当我有调用此过程的ADO.NET代码并执行此操作时:

return Convert.ToBoolean(sproc.ExecuteScalar());

Either true or false is returned. 返回true或false。

When I change the stored procedure to RETURN 1 or 0 instead of SELECT: 当我将存储过程更改为RETURN 1或0而不是SELECT时:

ALTER PROCEDURE [dbo].[AccountExists]
    @UserName nvarchar(16)
AS
IF EXISTS (SELECT Id FROM Account WHERE UserName=@UserName)
RETURN 1
ELSE RETURN 0 

sproc.ExecuteScalar() returns null. sproc.ExecuteScalar()返回null。 If I try sproc.ExecuteNonQuery() instead, -1 is returned. 如果我尝试使用sproc.ExecuteNonQuery(),则返回-1。

How do I get the result of a stored procedure with a RETURN in ADO.NET? 如何在ADO.NET中使用RETURN获取存储过程的结果?

I need AccountExists to RETURN instead of SELECT so I can have another stored procedure call it: 我需要AccountExists来RETURN而不是SELECT所以我可以让另一个存储过程调用它:

--another procedure to insert or update account

DECLARE @exists bit

EXEC @exists = [dbo].[AccountExists] @UserName 

IF @exists=1
--update account
ELSE
 --insert acocunt

Add a parameter, using ParameterDirection.ReturnValue . 使用ParameterDirection.ReturnValue添加ParameterDirection.ReturnValue The return value will be present in the paramter after the execution. 执行后,返回值将出现在参数中。

Also, to retrieve the result (or any other output parameter for that matter) from ADO.NET you have to loop through all returned result sets first (or skip them with NextResult) 此外,要从ADO.NET检索结果(或任何其他输出参数),您必须首先遍历所有返回的结果集(或使用NextResult跳过它们)

This means that if you have a procedure defined like this: 这意味着如果您有一个这样定义的过程:

CREATE PROC Test(@x INT OUT) AS
    SELECT * From TestTable
    SELECT @x = 1

And try to do this: 并尝试这样做:

SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Test"
cmd.Parameters.Add("@x", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.Parameters.Add("@retval", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

cmd.Execute();
int? x = cmd.Parameters["@x"].Value is DBNull ? null : (int?)cmd.Parameters["@x"].Value;

Then x will contain null. 然后x将包含null。 To make it work, you have to execute the procedure like: 要使其工作,您必须执行以下过程:

using (var rdr = cmd.ExecuteReader()) {
    while (rdr.Read())
        MaybeDoSomething;
}
int? x = cmd.Parameters["@x"].Value is DBNull ? null : (int?)cmd.Parameters["@x"].Value;

In the latter case, x will contain 1 as expected. 在后一种情况下,x将按预期包含1。

ExecuteScalar returns the first column of the first row. ExecuteScalar返回第一行的第一列。 Since you were no longer selecting, and creating a resultset, that is why it was returning null. 由于您不再选择并创建结果集,因此它返回null。 Just as FYI. 就像FYI一样。 John Saunders has the correct answer. 约翰桑德斯有正确的答案。

I tried the other solutions with my setup and they did not work but I'm using VB6 & ADO 6.x. 我用我的设置尝试了其他解决方案但它们没有用,但我使用的是VB6和ADO 6.x. I also want to point out that a proc return of 0 indicates successful. 我还想指出proc返回0表示成功。 Don't forget there are functions available too which don't have that convention. 不要忘记有些功能也没有那种惯例。 Found this on MSDN and it did work for me: 在MSDN上找到它,它确实对我有用:

Debug.Print "starting at ..." & TimeValue(Now)

Dim cn As New ADODB.Connection
Dim cmd As New ADODB.Command
'These are two possible connection strings. You could also have Integrated Security instead of these for SqS for security
'cn.ConnectionString = "Data Source=[yourserver];User ID=[youruser];Password=[yourpw];Initial Catalog=[yourdb];Provider=SQLNCLI10.1;Application Name=[yourapp]"
cn.ConnectionString = "Data Source=[yours];User ID=[youruser];Password=[yourpassword];Initial Catalog=[Yourdb];Provider=sqloledb;Application Name=[yourapp]"
cn.Open

cmd.ActiveConnection = cn
cmd.CommandText = "AccountExists"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Append cmd.CreateParameter(, adInteger, adParamReturnValue)
cmd.Parameters.Append cmd.CreateParameter("UserName",adVarChar, adParamInput, 16, UserNameInVB)

cmd.Execute
Debug.Print "Returnval: " & cmd.Parameters(0)
cn.Close

Set cmd = Nothing
Set cn = Nothing

Debug.Print "finished at ..." & TimeValue(Now)

The results will appear in the immediate window when running this (Debug.Print) 运行此结果时,结果将显示在即时窗口中(Debug.Print)

Several ways are possible to get values back using VBA: 有几种方法可以使用VBA获取值:

  1. Recordset 记录
  2. Count of records affected (only for Insert/Update/Delete otherwise -1) 受影响的记录数(仅适用于插入/更新/删除,否则为-1)
  3. Output parameter 输出参数
  4. Return value 返回值

My code demonstrates all four. 我的代码演示了所有四个。 Here is a stored procedure that returns a value: 这是一个返回值的存储过程:

Create PROCEDURE CheckExpedite
    @InputX  varchar(10),
    @InputY int,
    @HasExpedite int out
AS
BEGIN
    Select @HasExpedite = 9 from <Table>
    where Column2 = @InputX and Column3 = @InputY

    If @HasExpedite = 9
        Return 2
    Else
        Return 3
End

Here is the sub I use in Excel VBA. 这是我在Excel VBA中使用的子。 You'll need reference to Microsoft ActiveX Data Objects 2.8 Library. 您需要参考Microsoft ActiveX Data Objects 2.8 Library。

Sub CheckValue()

    Dim InputX As String: InputX = "6000"
    Dim InputY As Integer: InputY = 2014

    'open connnection
    Dim ACon As New Connection
    ACon.Open ("Provider=SQLOLEDB;Data Source=<SqlServer>;" & _
        "Initial Catalog=<Table>;Integrated Security=SSPI")

    'set command
    Dim ACmd As New Command
    Set ACmd.ActiveConnection = ACon
    ACmd.CommandText = "CheckExpedite"
    ACmd.CommandType = adCmdStoredProc

    'Return value must be first parameter else you'll get error from too many parameters
    'Procedure or function "Name" has too many arguments specified.
    ACmd.Parameters.Append ACmd.CreateParameter("ReturnValue", adInteger, adParamReturnValue)
    ACmd.Parameters.Append ACmd.CreateParameter("InputX", adVarChar, adParamInput, 10, InputX)
    ACmd.Parameters.Append ACmd.CreateParameter("InputY", adInteger, adParamInput, 6, InputY)
    ACmd.Parameters.Append ACmd.CreateParameter("HasExpedite", adInteger, adParamOutput)

    Dim RS As Recordset
    Dim RecordsAffected As Long

    'execute query that returns value
    Call ACmd.Execute(RecordsAffected:=RecordsAffected, Options:=adExecuteNoRecords)

    'execute query that returns recordset
    'Set RS = ACmd.Execute(RecordsAffected:=RecordsAffected)

    'get records affected, return value and output parameter
    Debug.Print "Records affected: " & RecordsAffected
    Debug.Print "Return value: " & ACmd.Parameters("ReturnValue")
    Debug.Print "Output param: " & ACmd.Parameters("HasExpedite")

    'use record set here
    '...

    'close
    If Not RS Is Nothing Then RS.Close
    ACon.Close

End Sub

Just some advice, but by default, a Stored Procedure returns 0 unless you specify something else. 只是一些建议,但默认情况下,除非您指定其他内容,否则存储过程将返回0。 For this reason, 0 is often used to designate success and non-zero values are used to specify return error conditions. 因此,0通常用于指定成功,非零值用于指定返回错误条件。 I would go with John's suggestion , or use an output parameter 我会考虑约翰的建议 ,或使用output parameter

If you are planing on using it like the example below AccountExists might be better off as a function. 如果您正在计划使用它,如下面的示例,AccountExists可能会更好地作为一个功能。

Otherwise you should still be able to get the result of the stored procedure by calling it from another one by doing a select on the result. 否则,您仍然可以通过对结果进行选择来从另一个调用存储过程的结果来获取存储过程的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM