Update with except statement

自作多情 提交于 2019-12-25 03:03:05

问题


This is my query

SELECT PageVisit_ID,TargetSite_ID FROM [A].Datawarehouse.mi.ctb_PageEvent WITH (NOLOCK)
 EXCEPT 
 SELECT PageVisit_ID ,TargetSite_ID FROM [B].Datawarehouse.mi.ctb_PageEvent WITH (NOLOCK)

these two tables from two servers. I need to update targetsite_id in [A].Datawarehouse.mi.ctb_PageEvent records from [B].Datawarehouse.mi.ctb_PageEvent only matched with above query results.


回答1:


Try this

DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

MERGE INTO [A].Datawarehouse.mi.ctb_PageEvent AS Target
USING ( SELECT PageVisit_ID ,TargetSite_ID FROM [B].Datawarehouse.mi.ctb_PageEvent WITH (NOLOCK)) AS SOURCE
ON Target.TargetSite_ID = Source.TargetSite_ID 
WHEN MATCHED THEN
    //UPDATE OR do nothing
WHEN NOT MATCHED BY TARGET THEN
    //INSERT 
OUTPUT $action INTO @SummaryOfChanges;

Please refer to SQL SERVER – Merge Operations – Insert, Update, Delete in Single Execution. my solution just gives a basic idea on how to do this. It might not work 100% initially. Just tweak it once you understand the logic



来源:https://stackoverflow.com/questions/12462560/update-with-except-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!