【发布时间】:2016-05-24 12:56:20
【问题描述】:
我有一个目标表 T 和一个源表 S。
当 S 中有一行不存在于 T 中时,我只想在某些条件为真时将其插入 T 中。
这是我目前的代码:
merge TargetTable as target
using SourceTable as source on (source.Id = target.Id)
when not matched by target then
--how to do this:
-- if exists (source.Name) then delete from source and later perform this insert
insert ([Id], [Name])
values (source.[Id], source.[Name])
;
name 列是target 表的主键。因此,如果我运行上述查询,则会收到主键违规错误。因此,首先我需要删除目标中的现有名称,然后再插入具有新 ID 的相同名称。
我怎样才能做到这一点?
【问题讨论】:
标签: sql-server tsql