ExecuteScalar returns null or DBNull (development or production server)

混江龙づ霸主 提交于 2019-11-28 11:10:51
Davide Piras

Clearly in production you have either a NULL returned from the command execution or something different in the connectionstring or whatever; as a general rule you should always test for DBNull before casting/converting directly to another type the result of ExecuteScalar.

Check Rein's answer here (and vote him up) for his nice suggested solution:

Unable to cast object of type 'System.DBNull' to type 'System.String`

ExecuteScalar returns DBNull for null value from query and null for no result. Maybe on your development server it never occured (null result from query).

Use the ISNULL() function in your SQL.

ISNULL ( check_expression , replacement_value )

ie...

SELECT ISNULL(SUM(Price),0) FROM Order

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