SQL Count()函数。和设置变量

时间:2011-07-02 10:18:26

标签: c# asp.net sql

    public void GetUsersDetails(Guid i)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("DECLARE @NumberOfThreadsByOneUser smallint;");
    sb.Append(" SET=(SELECT COUNT(t.threadID)");
    sb.Append(" FROM Threads AS t");
    sb.Append(" INNER JOIN Users AS u ON u.UsersID=t.UsersID");
    sb.Append(" WHERE u.UsersID=@UserID)");

    string myConnectionString = AllQuestionsPresented.connectionString;
    using (SqlConnection conn = new SqlConnection())
    {
        SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
        cmd.Parameters.Add("UserID", SqlDbType.UniqueIdentifier).Value = i;
        SqlDataReader dr = cmd.ExecuteReader();


 dr.Read();
     QA = (Int32.TryParse(dr["NumberOfThreadsByOneUser"].ToString(), out result3)) ? int.Parse(dr["Replies"].ToString()) : 0;
    }
}

我写了一个SQL语句,我想要得到的是用户提交的线程数。所以我宣布了一个smallint变量。但我不确定我的sql语句的语法。我想从结果中读取。 QA int属性应该接收该计数..

1 个答案:

答案 0 :(得分:4)

使用select代替set根据查询分配变量:

sb.Append(" SELECT @NumberOfThreadsByOneUser = (SELECT COUNT(t.threadID)");

要使用输出变量,请不要在SQL中声明它,而是传递它:

cmd.Parameters.Add("@NumberOfThreadsByOneUser").ParameterDirection = 
    ParameterDirection.InputOutput;

然后在命令执行后,您可以检索它:

var result = cmd.Parameters("@NumberOfThreadsByOneUser").Value

或者,使用reader方法,不要在SQL中声明变量,也不要将其作为参数传递。

 sb.Append(" SELECT COUNT(t.threadID) as ThreadCount");
 ....
 sb.Append(" WHERE u.UsersID=@UserID"); // <-- no closing )

读起来像:

var QA = (int) cmd.ExecuteScalar();

或者:

var read = cmd.ExecuteReader();
read.Read(); // <-- Gotta move to the first row
var QA = (int) read["ThreadCount"]; // <-- or whatever your column alias is