MERGE Example in MSSQL T-SQL
SIMPLE MERGE EXAMPLE FOR TSQL.
The example assumes that we are working with two tables of the same structure (in real life, this condition is not necessary).
Tables TargetTable and SourceTable consist of only two fields:
Id - some identifier.
Name - object name.
In the example below, we check for all records from SourceTable - whether there is a record in the TargetTable with a similar Id and if it exists, then change the Name field in TargetTable, and if it does not exist, then add a record to TargetTable from SourceTable in its entirety.
MERGE TargetTable AS target -- таблица которую будем менять, таблица приемник
USING (SELECT Id, Name FROM SourceTable) AS source
ON (target.Id = source.Id) -- условие по которому сопоставляем источник и приемник
WHEN MATCHED AND target.Name!=source.Name -- Если такой уже есть, то проверяем не совпадает ли Name и если не совпадает то меняем
THEN UPDATE SET target.Name = source.Name -- обновляем
WHEN NOT MATCHED -- если такого Id нет в таблице target то добавляем
THEN INSERT VALUES(source.Id, source.Name) -- добавление записи
That's all.
Comments (0)
No comments yet.