After ExecuteScalar: Object reference not set etc

前端 未结 3 1765
醉酒成梦
醉酒成梦 2021-01-18 14:32

What code I should add to accept null from WHERE statement.

{
    int numApprovals = 0;
    string sql = \"SELECT COUNT(Type) AS OpenforApproval \" +
                


        
3条回答
  •  遇见更好的自我
    2021-01-18 15:21

    Just:

    WHERE Type IN (2, 3, 4, 5, 6, 8, 13, 14, 16, 22) OR Type IS NULL
    

    But I'm not at all convinced that's what you really want, or the cause of the problem.

    If you're getting an exception in the C# code, it's not going to be from the where clause.

    I'm concerned by the fact that your connection seems to be reusing an existing variable, by the way. Bad idea. It should almost certainly be a local variable. You can also make your code simpler by returning from the middle of it:

    string sql = ...;
    
    using (var cn = new SqlConnection(ConnectionString()))
    {
        cn.Open();
        using (cmd = new SqlCommand(sql, cn))
        {
            cmd.CommandType = CommandType.Text;
            return (int) cmd.ExecuteScalar();
        }
    }    
    

    If the problem is as Jamie says, that ExecuteScalar is returning null, the easiest way of getting round that is to cast it to a nullable int and use the null coalescing operator:

    return (int?) cmd.ExecuteScalar() ?? 0;
    

提交回复
热议问题