--Creating the tables and insert some test datacreate table tbl (i int not null primary key, c char(5))goinsert into tbl (i,c)select 1, 'abc'union select 2, 'def'union select 3, 'ghi'gocreate table StagingTbl (i int not null primary key, c char(5))goinsert into StagingTbl (i,c)select 3, 'ghijk'union select 4, 'lmnop'go--First step is to update column c according to i--I do it with an update statement that uses--from clause. You can read about it in BOLupdate tblset tbl.c = StagingTbl.cfrom tbl inner join StagingTbl on tbl.i = StagingTbl.i--The insert is done with select that is doing a left--join and inserts only records that were not found--in tbl1.insert into tbl (i,c)select StagingTbl.i, StagingTbl.cfrom StagingTbl left join tbl on StagingTbl.i = tbl.iwhere tbl.i is nullgo--Check the resultsselect * from Tbl--cleanupdrop table tblgodrop table StagingTbl
--DROP TABLE #Destination, #StagingCREATE TABLE #Destination (a INT IDENTITY(1,1) PRIMARY KEY, Data VARCHAR(36) NULL)CREATE TABLE #Staging (a INT IDENTITY(5,1) PRIMARY KEY, Data VARCHAR(36) NULL)-- Test dataSET NOCOUNT ONGOINSERT #Destination (Data) SELECT '';INSERT #Staging (Data) SELECT CONVERT(VARCHAR(36), NEWID());GO 10-- Show the 'before'SELECT * FROM #Destination; SELECT * FROM #StagingDECLARE @KeysInserted TABLE (a INT PRIMARY KEY)SET IDENTITY_INSERT #Destination ON-- Insert new rows, remembering the keysINSERT #Destination (a, Data)OUTPUT inserted.a INTO @KeysInsertedSELECT S.a, S.DataFROM #Staging AS SWHERE NOT EXISTS (SELECT 1 FROM #Destination AS D WHERE S.a = D.a)SET IDENTITY_INSERT #Destination OFF-- UpdateUPDATE DSET Data = S.DataFROM #Staging AS SJOIN #Destination AS D ON D.a = S.aWHERE NOT EXISTS (SELECT 1 FROM @KeysInserted AS KI WHERE KI.a = S.a)-- The 'after'SELECT *FROM #Destination