Not logged in - Login

Add records for a new table

The following illustrates an example of using a MERGE statement to insert/update setup/master records into a table.


;with cteSrc as (
   SELECT *
   from ( values
      (1, 36001, 'Value 1', 'Unit 1', 'Description 1', 'admin', '2019-04-17T13:02:38.100', 'admin', '2019-04-17T13:02:38.100', newid())
      , (2, 36002, 'Value 2', 'Unit 2', 'Description 2', 'admin', '2019-04-17T13:03:05.463', 'admin', '2019-04-17T13:03:05.463', newid())
      , (3, 36002, 'Value 3', 'Unit 3', 'Description 3', 'admin', '2019-04-17T13:03:05.463', 'admin', '2019-04-17T13:03:05.463', newid())
      , (4, 36002, 'Value 4', 'Unit 4', 'Description 4', 'admin', '2019-04-17T13:03:05.463', 'admin', '2019-04-17T13:03:05.463', newid())
   ) as src([RowNum], [ConstantID], [ConstantName], [Units], [ConstantDescription], [sLastUser], [dtLastMod], [sCreatedBy], [dtCreateDate], [uuid])
)
merge into dbo.ConstantsMaster as dest -- target
using cteSrc as src on dest.ConstantName = src.ConstantName -- source
when matched then -- on match update
update set 
   dest.[ConstantName] = src.[ConstantName]
   , dest.[Units] = src.[Units]
   , dest.[ConstantDescription] = src.[ConstantDescription]
   , dest.[sLastUser] = src.[sLastUser]
   , dest.[dtLastMod] = src.[dtLastMod]
   --, dest.[sCreatedBy] = src.[sCreatedBy]
   --, dest.[dtCreateDate] = src.[dtCreateDate]
   --, dest.[uuid] = src.[uuid]
when not matched then -- insert missing
   insert ([ConstantName], [Units], [ConstantDescription], [sLastUser], [dtLastMod], [sCreatedBy], [dtCreateDate], [uuid])
   values ([ConstantName], [Units], [ConstantDescription], [sLastUser], [dtLastMod], [sCreatedBy], [dtCreateDate], [uuid])
--when not matched by source then delete       -- Uncomment this line to delete rows in the destination table that are missing from source
;