我正在查询数据,如果数据不存在,我插入它。如果是的话,我会做点别的事情:
SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = '" + orderNo + "';", connection);
SqlDataReader checkHeadReader = checkHead.ExecuteReader(CommandBehavior.SingleRow);
if (!checkHeadReader.HasRows)
{
checkHeadReader.Close();
addHead.ExecuteNonQuery();
}
但是我想知道是否有更短的编码方式?下面的代码会起作用吗?
SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = ' + orderNo + "';", connection);
if(checkHead.ExecuteReader(CommandBehavior.SingleRow).HasRows)
addHead.ExecuteNonQuery();
else //this order already exists
Server.Transfer(@"~/Views/Error.aspx");
答案 0 :(得分:3)
ExecuteScalar非常适用于此,例如
using (SqlCommand cmdCheck = new SqlCommand("Select Count(*) From Table Where Order_No = '" + orderNo + "'", connection))
{
int nExists = (int)cmdCheck.ExecuteScalar();
if (nExists==0) addHead.ExecuteNonQuery();
}