1

How to fetch the return value from a stored procedure?

enter image description here

I noticed that the stored procedure returns an integer on its own. I need to fetch it in C#.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vaibhav Jain
  • 33,887
  • 46
  • 110
  • 163

4 Answers4

2

You can make use of Return parameter in C# to get that value. Like as below

SqlParameter retval = sqlcomm.Parameters.Add("@return_value", SqlDbType.VarChar);
retval.Direction = ParameterDirection.ReturnValue;
sqlcomm.ExecuteNonQuery(); 
string retunvalue = (string)sqlcomm.Parameters["@return_value"].Value; 

Note your procedure must return a value to be able to fetch it:

create procedure [dbo].[usp_GetNewSeqVal]
       @SeqName nvarchar(255)
 as begin 
    declare @NewSeqVal int
    select @NewSeqVal  =1
   ---other statement
    return @NewSeqVal
 end
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

Check Following Code:

SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);
retval.Direction = ParameterDirection.ReturnValue;
sqlcomm.ExecuteNonQuery(); // MISSING
string retunvalue = (string)sqlcomm.Parameters["@b"].Value;

For further reference check link: Getting return value from stored procedure in C#

Community
  • 1
  • 1
Shivkant
  • 4,509
  • 1
  • 19
  • 16
0

In your SP, you need to return KategoriId. By default SP returns the number of rows affected by the latest insert, update or delete statement.

And mke sure you use proper data type in C# and in database column KategoriId to make this work. I had problems in past when database column was Decimal and I tried to assign the return value to an int and it never worked.

Suhas
  • 7,919
  • 5
  • 34
  • 54
-1

You can use output parameter in store procedure or use ExecuteScalar instead of ExecuteNonQuery.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
Manish Parakhiya
  • 3,732
  • 3
  • 22
  • 25
  • This is just all wrong: `ExecuteScalar` returns a single row, single column that's being **SELECTED** in the stored procedure - it does **NOT** return the value from the `RETURN x` statement! The `OUTPUT` parameter also has **nothing to do** with the value from the `RETURN` statement. – marc_s Aug 01 '12 at 07:17