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

十年热恋 提交于 2019-12-01 05:31:33

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.

mockobject

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.

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