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', sysdatetime(), 'admin', sysdatetime(), newid())
, (2, 36002, 'Value 2', 'Unit 2', 'Description 2', 'admin', sysdatetime(), 'admin', sysdatetime(), newid())
, (3, 36002, 'Value 3', 'Unit 3', 'Description 3', 'admin', sysdatetime(), 'admin', sysdatetime(), newid())
, (4, 36002, 'Value 4', 'Unit 4', 'Description 4', 'admin', sysdatetime(), 'admin', sysdatetime(), 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 -- Perform the matching on the ConstantName column (change this as appropriate)
when matched then -- on match update
update set
--dest.[ConstantName] = src.[ConstantName] -- no need to update the ConstantName column. We're matching on this field.
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
;
Last modified by Mohit @ 4/13/2025 11:29:37 AM