简体   繁体   English

从SQL表中删除具有多个列值的检查

[英]Deleting from SQL table with multiple column value checkings

I want to delete a row from an SQL table with multiple column value checking. 我想从SQL表中删除具有多列值检查的行。 I know how to do with it a single column value: 我知道如何处理单列值:

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();
}

However, what is the syntax for multiple column value checking? 但是,多列值检查的语法是什么? Also, how should I format the values if they are of Date (SQL) and Time7 (SQL) format? 另外,如果值是Date(SQL)和Time7(SQL)格式,我应该如何格式化它们?

Add one more clause to the where condition. 在where条件中再添加一个子句。 If you want to delete record which matches both condition, use AND ,and if you want to delete record which matches either one of the condition , then use OR 如果要删除同时符合两个条件的记录,请使用AND ;如果要删除符合任何一个条件的记录,请使用OR

Query to check both condition 查询以检查两个条件

string sqlStatement = "DELETE FROM Customers WHERE
          ColumnID = @ColumnID AND ColumnName2=@SecondValue";

Query to check either one condition 查询以检查任一条件

string sqlStatement = "DELETE FROM Customers WHERE 
            ColumnID = @ColumnID OR ColumnName2=@SecondValue";

So your code will be something like this 所以你的代码将是这样的

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
     }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM