Can you use cmd.ExecuteScalar when the sproc uses

2019-02-17 19:06发布

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?

2条回答
何必那么认真
2楼-- · 2019-02-17 19:27

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.

查看更多
我只想做你的唯一
3楼-- · 2019-02-17 19:47

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.

查看更多
登录 后发表回答