Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using select count(*) in c#

Tags:

c#

sql

asp.net

    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();

I am having the above query which returns number of rows, now my problem is how t read the output of the query? What i want is

 if(count=0)
{ 
   //Do
} 
else if(counnt >0)
{
    //Do something else
}
like image 681
Ishan Avatar asked Dec 22 '22 15:12

Ishan


1 Answers

You want to use ExecuteScalar(); instead which will return a single result.

So this line:

ddlistCmd.ExecuteReader();

should be:

ddlistCmd.ExecuteScalar();

which you can then assign to count after type casting the result.

like image 199
m.edmondson Avatar answered Jan 03 '23 00:01

m.edmondson