2013-03-27 92 views
0

我需要更新幾個共同具有相同字段的tabless。使用相同的SQLParameter更新多個表?

現在我有像這樣每個表的一個單獨的更新語句:

try 
     { 
      using (SqlConnection conn = new SqlConnection(cCon.getConn())) 
      { 

       using (SqlCommand cmd = conn.CreateCommand()) 
       { 
conn.Open(); 
        cmd.CommandText = "update table0 set active= 'N' where [email protected]"; 
        cmd.Parameters.Add(new SqlParameter("@id", id)); 
        cmd.ExecuteNonQuery(); 

        cmd.Parameters.Clear(); 
        cmd.CommandText = "update table1 set active= 'N' where id= @id "; 
        cmd.Parameters.Add(new SqlParameter("@id", id)); 
        cmd.ExecuteNonQuery(); 

        cmd.Parameters.Clear(); 
        cmd.CommandText = "update table2 set active= 'N' where id= @id " 
        cmd.Parameters.Add(new SqlParameter("@id", id)); 
        cmd.ExecuteNonQuery(); 

        cmd.Parameters.Clear(); 
        cmd.CommandText = "update table4 set active= 'N' where id= @id " 
        cmd.Parameters.Add(new SqlParameter("@id", id)); 
        cmd.ExecuteNonQuery(); 
       } 
      } 
     } 

我可以優化代碼,使其不太電話?可能將所有更新結合到1個commandtext中並只執行一次?

因爲它是所有相同的參數,我認爲這應該是可能的?或者我應該只是做一個存儲過程?

回答

1

理想情況下,你會調用存儲過程來處理這個問題。但是在一個批處理語句中使用相同的參數也可以:

cmd.CommandText = @"update table0 set active= 'N' where [email protected]; 
     update table1 set active= 'N' where id= @id; 
     update table2 set active= 'N' where id= @id; 
     update table4 set active= 'N' where id= @id;"; 
cmd.Parameters.Add(new SqlParameter("@id", id)); 
cmd.ExecuteNonQuery(); 
+0

我創建了一個存儲過程,謝謝! – 2013-03-27 18:18:04

0

您刪除

cmd.Parameters.Clear(); 

而且您使用此代碼只是一個時間

cmd.Parameters.Add(new SqlParameter("@id", id)); 

這樣:

cmd.CommandText = "update table0 set active= 'N' where [email protected]"; 
        cmd.Parameters.Add(new SqlParameter("@id", id)); 
        cmd.ExecuteNonQuery(); 


        cmd.CommandText = "update table1 set active= 'N' where id= @id "; 
        cmd.ExecuteNonQuery(); 

        cmd.CommandText = "update table2 set active= 'N' where id= @id " 
        cmd.ExecuteNonQuery(); 

        cmd.CommandText = "update table4 set active= 'N' where id= @id " 
        cmd.ExecuteNonQuery(); 
        cmd.Parameters.Clear(); 
1
const string query = @"update {0} set active= 'N' where [email protected];"; 

public string GetCommandText(string table) 
{ 
    return string.Format(query, table); 
} 

public IEnumerable<string> GetTables() 
{ 
    yield return "table0"; 
    yield return "table1"; 
    yield return "table2"; 
    yield return "table4"; 
} 

using (SqlCommand cmd = conn.CreateCommand()) 
{ 
    cmd.Parameters.Add(new SqlParameter("@id", id)); 
    cmd.CommandText = GetTables().Select(GetCommandText).Aggregate((s, s1) => s + s1); 

    conn.Open(); 
    cmd.ExecuteNonQuery(); 
}