views:

1906

answers:

2

Hi,

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?

+5  A: 

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.

NYSystemsAnalyst
+2  A: 

To answer your other question, (int) is a cast which is, in reality different than a conversion (Convert.ToInt32).

In a cast you are sort of saying that the object being cast is really of the type you are casting to so no real conversion/parsing is done. Since an int can't be null the cast is invalid when the object you are casting is null, and the exception is thrown.

With the convert some actualy parsing and logic takes place and it handles the situation where the object being converted is null.

There is some more info about this here.

mockedobject