ERROR ON:numApprovals =(int)cmd.ExecuteScalar();

时间:2009-07-06 15:19:03

标签: c# sql-server

public static int AwaitingApprovals()
{
    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;
}

4 个答案:

答案 0 :(得分:5)

您的查询似乎不正确。

一开始,我无法理解群体和群体的需要。你在SQL的末尾错过了一个“)”。

答案 1 :(得分:2)

你错过了一个括号,但是,你不需要GROUP BY和HAVING,你可以只有一个WHERE子句的附加部分。

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

答案 2 :(得分:1)

SQL语法错误。在没有任何右括号的HAVING之后你有一个左括号。添加右括号或只删除左括号。

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";

答案 3 :(得分:1)

您似乎在查询语句的末尾缺少右括号。不会 导致cmd.ExecuteScalar引发异常吗?