0

我想通过多列值检查从 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) 格式,我应该如何格式化这些值?

4

1 回答 1

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
     }    
}
于 2012-07-11T17:36:12.120 回答