我想从具有多列值检查的SQL表中删除一行。我知道如何处理单个列值:
SqlConnection connection = new SqlConnection("YourDatabaseConnectionString");
string sqlStatement = "DELETE FROM Customers WHERE ColumnID = @ColumnID";
try{
connection.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("@ColumnID", "SomeValueHere");
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
finally {
connection.Close();
}
但是,多列值检查的语法是什么?另外,如果值是Date(SQL)和Time7(SQL)格式,我应该如何格式化值?
答案 0 :(得分:1)
在where条件中再添加一个子句。如果您要删除与这两个条件匹配的记录,请使用 AND
,如果您要删除与其中一个条件匹配的记录,请使用 OR
强>
查询以检查两种情况
string sqlStatement = "DELETE FROM Customers WHERE
ColumnID = @ColumnID AND ColumnName2=@SecondValue";
查询以检查任一条件
string sqlStatement = "DELETE FROM Customers WHERE
ColumnID = @ColumnID OR ColumnName2=@SecondValue";
所以你的代码将是这样的
using(SqlConnection connection = new SqlConnection("YourDatabaseConnectionString"))
{
string sqlStatement = "DELETE FROM Customers WHERE ColumnID = @ColumnID AND ColumnName2=@SecondValue";
SqlCommand cmd = new SqlCommand(sqlStatement, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ColumnID", "SomeValueHere");
cmd.Parameters.AddWithValue("@SecondValue", "OtherValue");
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
//log error
}
}