2012-07-11 66 views
0

我想從具有多列值檢查的SQL表中刪除一行。我知道如何處理它的單列值:從具有多列值檢查的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(); 
} 

但是,多列值檢查的語法是什麼?另外,如果它們的日期(SQL)和Time7(SQL)格式的值應該如何格式化?

+1

你問的是如何使用AND和OR嗎?或者我在這裏錯過了什麼? – 2012-07-11 17:34:14

+0

我的意思是,但我想或者是以相同的方式工作? = / – CaTx 2012-07-11 17:41:50

回答

1

將where子句添加到where條件。如果你想刪除這兩個條件相匹配的記錄,使用AND,如果你想刪除其符合條件的任意一個記錄,然後用OR

查詢來檢查這兩個條件

string sqlStatement = "DELETE FROM Customers WHERE 
      ColumnID = @ColumnID AND [email protected]"; 

查詢來檢查任何一個條件

string sqlStatement = "DELETE FROM Customers WHERE 
      ColumnID = @ColumnID OR [email protected]"; 

所以你的代碼會是這樣

using(SqlConnection connection = new SqlConnection("YourDatabaseConnectionString")) 
{ 

    string sqlStatement = "DELETE FROM Customers WHERE ColumnID = @ColumnID AND [email protected]"; 
    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 
    }  
} 
相關問題