2016-10-15 98 views
1

我有一個表[ExistingTable]有三列:IDValueDateMERGE語句的問題

+----+------------------+ 
| ID | Value | Date  | 
+----+------------------+ 
| 1 | 100 |2016-01-01| 
| 1 | 200 |2016-01-01| 
| 1 | 300 |2016-01-01| 
| 2 | 200 |2016-01-01| 
| 2 | 300 |2016-01-01| 
+----+------------------+ 

,第二個表,[NewTable]

+----+------------+ 
| ID | Value  | 
+----+------------+ 
| 1 | 100  | 
| 1 | 200  | 
| 1 | 400  | 
| 2 | 200  | 
| 2 | 300  | 
+----+------------+ 

如果我寫這樣的合併聲明:

MERGE [ExistingTable] AS T1 
USING [NewTable] AS T2 ON (T1.[ID] = T2.[ID] AND T1.[Value] = T2.[Value]) 

WHEN NOT MATCHED THEN 
    INSERT([ID], [Value], [Date]) 
    VALUES(T2.[ID], T2.[Value], Getdate()) 

WHEN MATCHED THEN 
    UPDATE SET [Date] = Getdate(); 

查詢將插入ID = 1 AND Value = 400,它將更新所有其餘數據的日期。

,我要讓INSERT所有ID字段值,尚未匹配,在這個例子中,我希望得到這種結果:

+----+------------------+ 
| ID | Value | Date  | 
+----+------------------+ 
| 1 | 100 |2016-01-01| 
| 1 | 200 |2016-01-01| 
| 1 | 300 |2016-01-01| 
| 2 | 200 |2016-10-15| 
| 2 | 300 |2016-10-15| 
| 1 | 100 |2016-10-15| 
| 1 | 200 |2016-10-15| 
| 1 | 400 |2016-10-15| 
+----+------------------+ 

它是可以實現的與MERGE聲明?

+1

最終輸出的邏輯不清晰 – TheGameiswar

+1

*,但我想要對所有ID字段值進行INSERT,這些值尚未匹配* ...但是記錄「(1,100),(1,200)」* do *有一個匹配項。 –

+0

如果發生'NOT MATCH',我想插入所有來自'[NewTable]'具有**不匹配**'[ID]'值的數據的所有數據,希望它可以使用.. –

回答

0

我想這可能是與CTE和INSERT來完成:

;WITH cte AS (--here we will store all ID's that have 1 and more not matched Values 
SELECT n.ID 
FROM [NewTable] n 
LEFT JOIN ExistingTable e 
    ON n.ID = e.id and n.[Value] = e.[Value] 
WHERE e.ID IS NULL 
) 

INSERT INTO ExistingTable 
SELECT n.ID, 
     n.[Value], 
     GETDATE() 
FROM [NewTable] n 
INNER JOIN cte c 
    ON c.ID = n.ID 

然後如果從ExistingTable選擇您將獲得:

ID Value Date 
1 100  2016-01-01 
1 200  2016-01-01 
1 300  2016-01-01 
2 200  2016-01-01 
2 300  2016-01-01 
1 100  2016-10-15 
1 200  2016-10-15 
1 400  2016-10-15 
+0

謝謝@ gofr1,但當然,我需要與'MERGE'。我已經有臨時表和手動插入/更新語句的代碼,我只是想與合併 –

+0

爲什麼合併?插入數據不是你想要的,它是INSERT的工作。 – gofr1