我编写了这个SQL查询:
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();
我想添加一些if条件,如:
if (cmd2.ExecuteScalar()=="Null")
{....}
如何在我的查询没有答案时添加if条件?
答案 0 :(得分:8)
删除对cmd2.ExecuteNonQuery的调用,然后添加如下内容:
object maxCode = cmd2.ExecuteScalar();
if (maxCode == null)
{
// Null
}
else
{
// do something with maxCode, you probably want to cast - e.g. (int)maxCode
}
答案 1 :(得分:3)
你可以使用这样的阅读器:
这假设Code的类型是整数,因此根据需要进行更改
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
}
答案 2 :(得分:2)