问题
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