2013-07-09 24 views
1

可以說我有一個表格,其中包含以下數據。如何插入新行並從給定值集合中刪除缺少的行?

Id Value 
1 | A 
2 | B 
3 | C 

我需要將此表中的值與值的集合進行同步。我想刪除不在我的集合中的任何行,添加行並保留單獨的匹配行。

給定的值的這個集合:

C,D,E 

我期望表包含手術後:

Id Value 
3 | C 
4 | D 
5 | E 

我所知道的最需要多個查詢顯而易見的解決方案。我正在尋找的是可能的更高效的解決方案。我可以在這裏使用MERGE語句嗎?

編輯 - 收集值在C#的集合(list <string>),我使用的標準SqlConnection/SqlCommand的.NET中執行查詢。

這裏是我考慮去掉值的東西。但是這可能會被忽視,因爲我不得不做一些字符串連接來創建它。

DELETE FROM [MyTable] 
WHERE [Value] NOT IN ('C','D','E') 

但隨後添加它似乎像值我會創建多個IF NOT EXISTS然後插入我的收藏中的每個值的查詢語句。

+0

這是什麼樣的收集?這個集合如何獲得SQL?這是一個程序中的集合嗎(比如說,一個.NET應用程序中的Dictionary)或者什麼? – cost

+0

所以......你問是否合併2個表(你需要創建其中的一個)比檢查值是否在當前表中然後插入這些值更好? – BLaZuRE

+0

好問題。假設我在列表中包含這些值。對於這個應用程序,我使用了一個原始的SqlConnection/SqlCommand。這有幫助嗎? – Vyrotek

回答

0

好的,你的收藏是在C#列表中。這使得這更容易。這不是最有效的方法,因爲它涉及很多查詢,並且它可以更好地使用Dictionary,但是如果您沒有按時間並且不想使用字符串連接來解決這個問題,做一個複雜的查詢。

using (SqlConnection connection = new SqlConnection(.....)) 
{ 
    connection.Open; 

    using (SqlCommand command = new SqlCommand("SELECT ID, Value FROM Table")) 
    { 
     using (SqlDataReader reader = SqlCommand.ExecuteReader()) 
     { 
     while (reader.Read()) 
     { 
      if (THELIST.Contains(reader["Value"].ToString()) 
      { 

        THELIST.Remove(reader["Value"].ToString()); 
      } 
      else 
      { 
        //Execute a SqlCommand in here to do a DELETE where ID = reader["ID"] 
      } 

     } 

     } 

    } 

    //Now that you've deleted all the ones that aren't in this list, go through what's left in the list and insert them (only the ones that aren't in the database will be left, since you deleted them as they were found 

    foreach (string thing in THELIST) 
    { 
    //Execute a SqlCommand to do an insert into the database 
    } 

} 
1

我不認爲你可以在一個SQL語句做到這一點,但你可以創建一個存儲過程來完成這項工作:

create procedure upsertnewrecords(
    @collection varchar(max) 
) as 
begin 
    delete 
    from yourtable 
    where charindex(','+value+',', ','[email protected]+',') = 0 

    ;with cte as (
    select split.t.value('.', 'VARCHAR(100)') newvalue 
    from (
     select cast ('<M>' + replace(@collection, ',', '</M><M>') + '</M>' as xml) as String  
    ) t 
    cross apply String.nodes ('/M') AS Split(t) 
) 

    insert into yourtable 
    select newvalue 
    from cte 
    where newvalue not in 
    (select value from yourtable) 
end 

此存儲過程首先使用CHARINDEX刪除不在當前列表中的值,然後使用CROSS APPLY將您的逗號分隔列表轉換爲有價值的列表,最後通過一個公用表表達式插入這些列表。