简体   繁体   English

C#从存储过程获取返回值不起作用

[英]C# Getting Return Value from Stored Procedure Is Not Working

I am trying to run a stored procedure returning a single integer value and I can't figure out where its going wrong. 我试图运行一个存储过程返回一个整数值,我无法弄清楚它出错的地方。 From what I've read the following should work but is not and I can't see where I'm going wrong. 从我读到的内容中,以下内容应该有效,但不是,我无法看到我出错的地方。

Here is my stored procedure: 这是我的存储过程:

    ALTER PROCEDURE [dbo].[getDDNTempID]
    AS
    BEGIN
        declare @tempID int

        select top 1 @tempID = tempID from tblDDNHdr order by tempID asc
        if @tempID is null
            return 0
        else
            return @tempID
    END

Here is the code where I try to get the return value: 这是我尝试获取返回值的代码:

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand("getDDNTempID", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection.Open();
            Int32 tempID = (Int32)cmd.ExecuteScalar();
            if (tempID == 0) { tempID = -1; }
            return tempID;
        }

When this procedure is called I get a NullReferenceException and the line giving the error is: 调用此过程时,我得到一个NullReferenceException,给出错误的行是:

            Int32 tempID = (Int32)cmd.ExecuteScalar();

I would appreciate any guidance you guys could give. 我很感激你们给予的任何指导。

Thanks 谢谢

The return function in SQL Server is specifically to return completion codes to the calling function. SQL Server中的返回函数专门用于将完成代码返回给调用函数。 As such, the values available to be returned are limited. 因此,可返回的值是有限的。 What you need to do instead is to SELECT @tempID and treat it as a result set. 您需要做的是SELECT @tempID并将其视为结果集。

ExecuteScalar returns the value of the first column of the first row of the results. ExecuteScalar返回结果第一行第一列的值。 Your stored procedure does not return a result set. 您的存储过程不返回结果集。

Add a parameter to the SqlCommand.Parameters collection and set the Direction to ReturnValue . 将参数添加到SqlCommand.Parameters集合并将Direction设置为ReturnValue It will receive the return value from the stored procedure. 它将从存储过程接收返回值。

Please note that the return value is intended only for returning a status. 请注意,返回值仅用于返回状态。 You should use an OUTPUT parameter to return @TempId . 您应该使用OUTPUT参数来返回@TempId

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

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