By Wesley


2011-06-02 03:22:12 8 Comments

I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.

Stored procedure code:

ALTER procedure [dbo].[usp_GetNewSeqVal]
      @SeqName nvarchar(255)
as
begin
      declare @NewSeqVal int
      set NOCOUNT ON
      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName

      if @@rowcount = 0 begin
print 'Sequence does not exist'
            return
      end

      return @NewSeqVal
end

Code calling the stored procedure:

SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();

SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter param = new SqlParameter();

param = cmd.Parameters.Add("@SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";

SqlDataReader reader = cmd.ExecuteReader();

I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get the return value from my stored procedure? If more information is needed, please let me know.

8 comments

@Paul 2017-05-09 17:22:45

I had a similar problem with the SP call returning an error that an expected parameter was not included. My code was as follows.
Stored Procedure:

@Result int OUTPUT

And C#:

            SqlParameter result = cmd.Parameters.Add(new SqlParameter("@Result", DbType.Int32));
            result.Direction = ParameterDirection.ReturnValue;

In troubleshooting, I realized that the stored procedure was ACTUALLY looking for a direction of "InputOutput" so the following change fixed the problem.

            r

Result.Direction = ParameterDirection.InputOutput;

@RaSor 2016-11-07 12:50:29

The version of EnterpriseLibrary on my machine had other parameters. This was working:

        SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
        retval.Direction = System.Data.ParameterDirection.ReturnValue;
        cmd.Parameters.Add(retval);
        db.ExecuteNonQuery(cmd);
        object o = cmd.Parameters["@ReturnValue"].Value;

@AH. 2017-06-16 12:56:28

This is the correct answer - for me :-) Thanks.

@Rain 2014-11-21 05:22:54

I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah

Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;

@Gary 2014-09-04 21:00:45

I know this is old, but i stumbled on it with Google.

If you have a return value in your stored procedure say "Return 1" - not using output parameters.

You can do the following - "@RETURN_VALUE" is silently added to every command object. NO NEED TO EXPLICITLY ADD

    cmd.ExecuteNonQuery();
    rtn = (int)cmd.Parameters["@RETURN_VALUE"].Value;

@Michael 2014-11-10 18:05:48

Hi Gary. Do you happen to have a citation?

@joey 2016-08-19 22:22:46

I dont believe that the cmd instance will have a parameter named in RETURN_VALUE in the SqlParameterCollection unless it is added explicitly. Therefore, if you are considering taking the approach above by Gary, then ensure you have added cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.Int)); cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue; However, I do believe that you DO NOT have to add the @RETURN_VALUE to the stored procedure definition. Perhaps that is what Gary meant.

@Dunc 2013-10-31 11:54:08

Or if you're using EnterpriseLibrary rather than standard ADO.NET...

Database db = DatabaseFactory.CreateDatabase();
using (DbCommand cmd = db.GetStoredProcCommand("usp_GetNewSeqVal"))
{
    db.AddInParameter(cmd, "SeqName", DbType.String, "SeqNameValue");
    db.AddParameter(cmd, "RetVal", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);

    db.ExecuteNonQuery(cmd);

    var result = (int)cmd.Parameters["RetVal"].Value;
}

@Justin Dearing 2011-06-02 03:31:51

ExecuteScalar() will work, but an output parameter would be a superior solution.

@Soori 2016-03-07 14:30:01

ExecuteScalar() doesn't work, unless you "select" the return value.

@Aravind 2011-06-02 03:29:28

You can try using an output parameter. http://msdn.microsoft.com/en-us/library/ms378108.aspx

@Alex Aza 2011-06-02 03:27:48

You need to add return parameter to the command:

using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = parameterStatement.getQuery();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");

    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}

@muttley91 2014-02-03 19:42:58

Do you have to add @ReturnVal to the Stored Procedure as well?

@ufosnowcat 2014-12-10 09:27:57

No, you don't have to add to the sp (the return statement triggers filling the parameter marked with ReturnValue)

@varsha 2015-02-25 06:40:04

thanx i needed this

@Clay 2016-04-28 13:58:04

Doesn't matter what you name the return val parameter, btw.

@Oswaldo 2017-08-23 22:57:13

thanks a lot, I was looking for a way to properly get return value, this really worked for me. awesome!

@tony09uk 2017-11-16 08:28:48

Looking through SqlDbType enumeration, all the types are for returning only a single value. How do you define that a table of data is being returned?

@Manuel Hoffmann 2018-01-19 08:23:00

@tony09uk I don't think ReturnValue supports that. But you can simply not use return in your procedure and instead end the procedure with SELECT * FROM tableToReturn. In your programm, use an SqlDataAdapter to get the table from the select statement in your stored procedure just like you would get get the result of a normal SQL statement.

@Dan Guzman 2018-08-12 13:07:26

The stored procedure return value should be used only to indicate success (zero) or failure/warning (non-zero), not return data. Use an OUTPUT parameter or result set for that purpose.

Related Questions

Sponsored Content

39 Answered Questions

[SOLVED] How to return only the Date from a SQL Server DateTime datatype

10 Answered Questions

[SOLVED] Calling the base constructor in C#

  • 2008-08-15 07:39:23
  • lomaxx
  • 902263 View
  • 1287 Score
  • 10 Answer
  • Tags:   c# constructor

18 Answered Questions

[SOLVED] Function vs. Stored Procedure in SQL Server

16 Answered Questions

[SOLVED] Select columns from result set of stored procedure

14 Answered Questions

[SOLVED] How to return multiple values from a function?

22 Answered Questions

[SOLVED] Search text in stored procedure in SQL Server

25 Answered Questions

37 Answered Questions

1 Answered Questions

4 Answered Questions

[SOLVED] c# closing sqlconnection and sqldatareader or not?

Sponsored Content