2014-09-29 36 views
1
SQL Server合併聲明
MERGE DestinationTable AS D 
USING @SourceTable AS S 
ON D.Alternate_ID = S._ID 

WHEN MATCHED AND 
(
     D.Candidate_ID <> S.Candidate_ID OR ISNULL(D.Vacancy_ID,'') <> S.Vacancy_ID 
) 
THEN 
UPDATE SET 
    D.FName = S.FName, 
    D.Department = S.Department, 

WHEN NOT MATCHED BY TARGET 
THEN INSERT 
(
    Alternate_ID, 
    FName, 
    Department 
) 
    VALUES 
    (
    S.ID, 
    S.FName, 
    S.Department 
) 
WHEN NOT MATCHED BY SOURCE 
--How to add a where clause to the delete statement here 
THEN DELETE; --E.g WHERE D.Department <> 'HR' 

我在上面使用的MERGE語句刪除destinationTable會記錄如何添加一個地方,如果他們已經從源刪除條件爲刪除

是否有任何人知道如何可以將WHERE條件添加到Delete語句中?我只想從ColA等於特定常量字符串的目標中刪除。

+1

根據http://sqlstudies.com/2013/09/30/the-merge-statement-doesnt-have-a-where-clause/,您可以添加到何時不匹配的來源和D .Department <>'HR'THEN DELETE – 2014-09-29 09:39:00

回答

2

是的,有關MERGE的信息,請參閱MSDN article

[ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ] 
    THEN <merge_matched> ] [ ...n ] 

這是適用於您的查詢的NOT MATCHED BY SOURCE部分的文檔(假設COIA是在目標表中的列):

... 
WHEN NOT MATCHED BY SOURCE AND D.CoIA = 'YourValue' THEN 
DELETE; 

但是,一定要注意以下幾點:

MERGE語句最多可以有兩個不匹配的條款。如果指定了兩個子句,則第一個子句必須是 ,並附帶ANDclause_search_condition>子句。對於任何給定的 行,第二個WHEN NOT MATCHED BY SOURCE子句僅適用於第一個不是 的情況。如果有兩個WHEN NOT MATCHED BY SOURCE子句, 則必須指定一個UPDATE操作,並且必須指定一個DELETE 操作。 只有來自目標表的列可以在 < clause_search_condition>中引用。

相關問題