Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Condition for Query with Empty Result

Tags:

c#

sql

ado.net

I have written this SQL query:

 SqlCommand cmd2 = new SqlCommand();
        cmd2.Connection = new SqlConnection(Class1.CnnStr);
        cmd2.CommandText = "SELECT MAX(Code) FROM Table WHERE Number=@Number ";
        cmd2.Connection.Open();
        cmd2.Parameters.AddWithValue("@Number", Hidden_txt.Text);
        cmd2.ExecuteNonQuery();

and I would like to add some if condition like:

if (cmd2.ExecuteScalar()=="Null")
{....}

How can I add an if condition for when my query does not have an answer?

like image 250
Katy J Avatar asked Nov 12 '11 13:11

Katy J


3 Answers

You can use a reader like this:

This assumes that the type of Code is integer, so change as necessary

SqlDataReader reader = cmd2.ExecuteReader;
int code = 0;
if (reader.Read) {
     //whatever if it has a result
     code = reader.GetInt32(0);
} else {
    //Whatever if it finds nothing
}
like image 35
Jay Avatar answered Sep 23 '22 00:09

Jay


Remove the call to cmd2.ExecuteNonQuery, then add something like this:

object maxCode = cmd2.ExecuteScalar();
if (maxCode == null)
{
    // Null
}
else
{
    // do something with maxCode, you probably want to cast - e.g. (int)maxCode
}
like image 131
Matt Varblow Avatar answered Sep 21 '22 00:09

Matt Varblow


According to MSDN:

If the first column of the first row in the result set is not found, a null reference (Nothing in Visual Basic) is returned. If the value in the database is null, the query returns DBNull.Value.

So, you could just write:

if (cmd2.ExecuteScalar() == null)
{....}

Alternatively, you could use ExecuteReader, then check whether returned reader HasRows.

like image 39
Branko Dimitrijevic Avatar answered Sep 21 '22 00:09

Branko Dimitrijevic