在c#中使用select count(*)

时间:2011-04-18 11:03:19

标签: c# asp.net sql

    String dd_webCofig = ConfigurationManager.ConnectionStrings["server132"].ConnectionString;
    SqlConnection ddlistconn = new SqlConnection(dd_webCofig);
    ddlistconn.Open();

    string ddlist = "select count(*) from jud_order where complex_name=@a and case_no=@b and sign=@c and jud_order_date=@d and user_code=@e";
    SqlCommand ddlistCmd = new SqlCommand(ddlist, ddlistconn);
    ddlistCmd.Parameters.AddWithValue("a", "a");
    ddlistCmd.Parameters.AddWithValue("b", "a");
    ddlistCmd.Parameters.AddWithValue("c", "a");
    ddlistCmd.Parameters.AddWithValue("d", "a");
    ddlistCmd.Parameters.AddWithValue("e", "a");

    SqlDataReader myReader = ddlistCmd.ExecuteReader();

我有上面的查询返回行数,现在我的问题是如何读取查询的输出? 我想要的是

 if(count=0)
{ 
   //Do
} 
else if(counnt >0)
{
    //Do something else
}

3 个答案:

答案 0 :(得分:13)

您希望使用ExecuteScalar();而不是返回单个结果。

所以这一行:

ddlistCmd.ExecuteReader();

应该是:

ddlistCmd.ExecuteScalar();

然后您可以在输入结果后将其分配给count

答案 1 :(得分:0)

int result=ddlistCmd.ExecuteScalar();

答案 2 :(得分:-2)

尝试:

myReader.Read();
count= int.Parse(myReader[0].ToString());