2011-12-16 57 views
1

我使用SQL Server 2008來存儲我的數據,這樣的如何以有效的方式覆蓋數據庫中的重複數據?

index float not null, 
type int not null, 
value int not null, 

和(指數型)的表結構unique.there並不是兩個DATAS具有相同指數和同一類型。因此,當我將數據插入到表中時,我必須檢查(索引,類型)對在表中是否已經存在,如果存在,我使用update語句,否則,我直接插入它。但我認爲這是是不是一個有效的方法,因爲:

  1. 大部分數據」指數型對不存在的int table.so選擇操作是浪費,尤其是表是巨大的。

  2. 當我使用C#或其他CLR語言插入數據時,我無法使用批量複製或批量插入。

有沒有辦法直接覆蓋數據而不檢查它是否存在於表中?

回答

4

如果要更新或插入數據,您需要使用merge

merge MyTable t using (select @index index, @type type, @value value) s on 
    t.index = s.index 
    and t.type = s.type 
when not matched insert (index, type value) values (s.index, s.type, s.value) 
when matched update set value = s.value; 

這將着眼於你的價值觀,並採取適當的行動。

在C#中做到這一點,你必須使用傳統的SqlClient

SqlConnection conn = new SqlConnection("Data Source=dbserver;Initial Catalog=dbname;Integrated Security=SSPI;"); 
SqlCommand comm = new SqlCommand(); 
conn.Open(); 
comm.Connection = conn; 

//Add in your values here 
comm.Parameters.AddWithValue("@index", index); 
comm.Parameters.AddWithValue("@type", type); 
comm.Parameters.AddWithValue("@value", value); 

comm.CommandText = 
    "merge MyTable t using (select @index index, @type type, @value value) s on " + 
     "t.index = s.index and t.type = s.type " + 
    "when not matched insert (index, type value) values (s.index, s.type, s.value) " + 
    "when matched update set value = s.value;" 
comm.ExecuteNonQuery(); 

comm.Dispose(); 
conn.Close(); 
conn.Dispose(); 
+0

如果您爲兩個col創建了一個唯一約束,那麼您不允許插入具有相同索引,類型的數據。當你使用CLR語言來執行批量插入時,你會得到一個異常。 – storm 2011-12-16 18:07:23

+0

更新爲包含'merge`語句 – Eric 2011-12-16 18:14:00

+0

好的,我會測試這些不同的方法並找出哪一個更好。 – storm 2011-12-16 18:14:41

0

你應該(index, type)composite primary key(又名複合鍵)。

這將確保表只能有唯一的這些對(我假設該表沒有主鍵)。

如果表具有主鍵,則可以將UNIQUE constraint添加到具有相似效果的列上。

一旦定義,這意味着任何插入重複對的嘗試都會失敗。

0

其他答案建議約束條件。創建約束意味着您將執行觸發錯誤的插入語句。下一步(在創建約束之後)類似於INSERT ON DUPLICATE KEY UPDATE,它顯然具有與Sql Server等效的功能。