ExecuteScalar returns null or DBNull (development or production server)

后端 未结 3 1442
温柔的废话
温柔的废话 2020-12-10 13:53

I\'m trying to add a column to an existing DataRow in C#. Afterwards the column will be filled with a single value from my database.

DataRow dr already

相关标签:
3条回答
  • 2020-12-10 14:16

    Use the ISNULL() function in your SQL.

    ISNULL ( check_expression , replacement_value )

    ie...

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

    0 讨论(0)
  • 2020-12-10 14:17

    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).

    0 讨论(0)
  • 2020-12-10 14:32

    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`

    0 讨论(0)
提交回复
热议问题