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

扶醉桌前 提交于 2019-12-01 03:37:04

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/520735/can-you-use-cmd-executescalar-when-the-sproc-uses-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!