在ExecuteScalar之后:未设置对象引用等

时间:2009-07-10 14:16:47

标签: c# sql

我应该添加什么代码来接受来自WHERE语句的null。

{
    int numApprovals = 0;
    string sql = "SELECT COUNT(Type) AS OpenforApproval " +
       "FROM dbo.LeaveRequest " +
       "WHERE Type IN (2, 3, 4, 5, 6, 8, 13, 14, 16, 22) " +
       "GROUP BY MgtApproval " +
       "HAVING MgtApproval IS NULL";
       //"SELECT COUNT(EffectiveDate) AS OpenforApproval FROM LeaveRequest GROUP BY TimeStampApproval HAVING (TimeStampApproval IS NULL)";

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

    return numApprovals;
}

3 个答案:

答案 0 :(得分:12)

只需:

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

但我完全不相信你真正想要的,或问题的原因。

如果您在C#代码中遇到异常,那么它不会来自where子句。

顺便说一句,我担心您的连接似乎正在重用现有变量。馊主意。它几乎肯定是一个局部变量。您还可以通过从中间返回来使代码更简单:

string sql = ...;

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

如果问题与Jamie说的那样,那就是ExecuteScalar返回null,最简单的方法就是将它转换为可以为空的int并使用null合并运算符:

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

答案 1 :(得分:2)

问题可能是直接转换为int。如果cmd.ExecuteScalar()返回null,则抛出异常。在这种情况下,您需要决定返回什么。对于此示例,如果cmd.ExecuteScalar()返回null

,则返回0
using (cn = new SqlConnection(ConnectionString()))
{
    cn.Open();
    using (cmd = new SqlCommand(sql, cn))
    {
        cmd.CommandType = CommandType.Text;
        object result = cmd.ExecuteScalar();
        numApprovals = result == null ? 0 : (int)result;
    }
}

return numApprovals;

答案 2 :(得分:1)

顺便说一句,将多行字符串格式化为更简单/更清晰:

string sql = 
@"SELECT COUNT(Type) AS OpenforApproval
FROM dbo.LeaveRequest
WHERE Type IN (2, 3, 4, 5, 6, 8, 13, 14, 16, 22)
GROUP BY MgtApproval
HAVING MgtApproval IS NULL";