5

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:

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

I would appreciate any guidance you guys could give.

Thanks

1

2 Answers 2

3

The return function in SQL Server is specifically to return completion codes to the calling function. 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.

1
  • I tried what you described and altered my stored procedure and it worked perfectly - thanks. I didn't realise the limitations of the return function
    – james33
    Sep 19, 2013 at 6:24
2

ExecuteScalar returns the value of the first column of the first row of the results. Your stored procedure does not return a result set.

Add a parameter to the SqlCommand.Parameters collection and set the Direction to 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.

1
  • 1
    I tried this solution as well and it also worked perfectly. More than one way to skin a cat I guess. (Why do people skin cats anyway?)
    – james33
    Sep 19, 2013 at 6:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.