我有一个目标表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的相同名称。
我怎样才能做到这一点?
答案 0 :(得分:3)
在MERGE语句中,因为您正在检查条件TARGET.Id = SOURCE.Id,并且当您要在插入之前删除名称时,TARGET表中可能不存在相同的Id。那么,您是否可以先尝试执行此MERGE语句,检查TARGET表中是否存在[Name]并删除它然后执行MERGE语句?
MERGE TargetTable AS TARGET
USING SourceTable AS SOURCE
ON (TARGET.Name = SOURCE.Name)
WHEN MATCHED THEN
DELETE;
GO
MERGE TargetTable AS TARGET
USING SourceTable AS SOURCE
ON (TARGET.Id = SOURCE.Id)
WHEN NOT MATCHED BY TARGET THEN
INSERT (Id,Name)
VALUES(SOURCE.Id,SOURCE.Name);