Click here to Skip to main content
15,919,028 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I write this sql query:
C#
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 want to put some (IF) such as:
C#
if (cmd2.ExecuteScalar()=="Null")
{....}

for sometimes that my query does not have answer but it doesn't work. what should I do to put some IF for sometimes that my query does not have any answer?
Posted
Updated 12-Nov-11 2:05am
v2

You can edit your query like this :
SQL
SELECT MAX(ISNULL(Code,0)) FROM Table WHERE Number=@Number
 
Share this answer
 
Comments
Amir Mahfoozi 14-Nov-11 7:58am    
+5 good solution ;)
Mehdi Gholam 14-Nov-11 8:51am    
Cheers
Use a try catch block instead...
Execute your SQL Command and "connection.open" statements in the try clause...

Also since execute non query returns number of rows affected, you can check if the number of rows returned is greater than 0


PS. Use stored Procedures rather than fire the query directly from the code itself
 
Share this answer
 
Hi,
you can try by

C#
int result=-1;
result=cmd2.ExecuteNonQuery();

if(result != -1)
{

}


it will work proper. Because ExecuteNonQuery returns an "int" value indicating the no. of rows affected.so you can try this...
 
Share this answer
 
v2
Comments
Dalek Dave 12-Nov-11 8:58am    
I put a code block in for readability.
Try:
C#
if (cmd2.ExecuteScalar() == DBNull.Value)
   {
   ...
   }
 
Share this answer
 
Comments
kitykity 12-Nov-11 8:46am    
thank you veryyyyy much

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900