Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use cmd.ExecuteScalar when the sproc uses RETURN @value

Can you use

int blah = Convert.ToInt32(cmd.ExecuteScalar());

When the sproc's last statement does:

RETURN @value

I can only get it to work if it does:

SELECT @value

Also, this gives me a object null exception:

int blah = (int)cmd.ExecuteScalar();

isn't convert.toint32 and (int) the same thing but one is a wrapper of the other?

like image 549
Blankman Avatar asked Feb 06 '09 15:02

Blankman


People also ask

What does ExecuteScalar return?

ExecuteScalar() MethodExecuteScalar() method is used to retrieve a single value from database. It executes the defined query and returns the value in the first column of the first row in the selected result set and ignores all other columns and rows in the result set.

What is use of ExecuteScalar () method?

Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.

What is command ExecuteScalar?

ExecuteScalar method is used to execute SQL Commands or storeprocedure, after executing return a single value from the database. It also returns the first column of the first row in the result set from a database.


1 Answers

No, you cannot. The ExecuteScalar() method is designed to return as single value that is returned in a result set. Basically, the value in the first column of the first row returned.

To get the return value, you need to add a parameter to your SQLCommand object. Use the name "@RETURN_VALUE" and specify a parameter direction of Return when creating the parameter object. You can then use the ExecuteNonQuery() method.

I must note that IMO, stored procedure return values should simply indicate the status of the procedure. All data should be returned through result sets or output parameters.

like image 176
DCNYAM Avatar answered Sep 24 '22 01:09

DCNYAM