如果要更新或插入數據,您需要使用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();
如果您爲兩個col創建了一個唯一約束,那麼您不允許插入具有相同索引,類型的數據。當你使用CLR語言來執行批量插入時,你會得到一個異常。 – storm 2011-12-16 18:07:23
更新爲包含'merge`語句 – Eric 2011-12-16 18:14:00
好的,我會測試這些不同的方法並找出哪一個更好。 – storm 2011-12-16 18:14:41