开发者

How to update table with only new or changed values?

Here is my query but it makes lots of doubles and I need insert new and (maybe) update changed values.

INSERT INTO [FRIIB].[dbo].[ArchiveAnalog] 
                       开发者_如何学Go (Date, ID, Value)
                        SELECT Date, ID, Value
                            FROM [LinkedOne].[FRIIB].[dbo].[ArchiveAnalog]

My problem is I need to compare not single value , I need to compare whole node with 3 values to check if there is existing ones.

thank you.


Assuming SQL Server 2008 or above, use MERGE e.g.

MERGE INTO [FRIIB].[dbo].[ArchiveAnalog] 
USING (
       SELECT [Date], ID, [Value]
         FROM [LinkedOne].[FRIIB].[dbo].[ArchiveAnalog]
      ) AS source ([Date], ID, [Value])
   ON [Date] = source.[Date]
      AND ID = source.ID
      AND [Value] = source.[Value]
WHEN NOT MATCHED THEN
   INSERT ([Date], ID, [Value])
      VALUES ([Date], ID, [Value]);


To insert the missing values, following would do

INSERT INTO [FRIIB].[dbo].[ArchiveAnalog] (Date, ID, Value)
SELECT  laa.Date, laa.ID, laa.Value
FROM    [LinkedOne].[FRIIB].[dbo].[ArchiveAnalog] laa
        LEFT OUTER JOIN [FRIIB].[dbo].[ArchiveAnalog] aa ON aa.Date = laa.Date
                                                            AND aa.ID = laa.ID
                                                            AND aa.Value = laa.Value
WHERE   aa.ID IS NULL                                                            

To update existing values you might want to look into the MERGE statement

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜