我在我的merge语句中注意到,源表中有PackageId
为0
的行。这些记录不应插入到目标表中。所以我想在我的INSERT上设置这种条件。
MERGE MyTargetTable AS TARGET
USING MySourceTable AS SOURCE
ON (SOURCE.orderidHash = TARGET.Id)
WHEN MATCHED AND (TARGET.CustomerId <> SOURCE.CustomerId
OR TARGET.PackageId <> SOURCE.packageid
OR TARGET.TypeId <> SOURCE.ordertypeid
OR TARGET.Created <> SOURCE.Created
OR TARGET.Updated <> SOURCE.Changed)
THEN
UPDATE SET TARGET.CustomerId = SOURCE.customeridHash,
TARGET.PackageId = SOURCE.packageid,
TARGET.TypeId = SOURCE.ordertypeid,
TARGET.Created = SOURCE.Created,
TARGET.Updated = SOURCE.Changed
WHEN NOT MATCHED BY TARGET
INSERT (
Id,
CustomerId,
PackageId,
TypeId,
Created,
Updated
)
VALUES (
SOURCE.orderidHash,
SOURCE.customeridHash,
SOURCE.packageid,
SOURCE.ordertypeid,
SOURCE.Created,
SOURCE.changed
)
WHEN NOT MATCHED BY SOURCE THEN DELETE;
在上述声明中,我应该在哪里WHERE PackageId <> 0
?当我将条件放在WHEN NOT MATCHED BY TARGET
之后时,我收到错误消息:
MERGE语句与FOREIGN KEY约束“ FK_MyTargetTable_DimCustomer”冲突。数据库MyDatabase的表DimCustomer的列ID中发生了冲突。
MyTargetTable.CustomerId
是DimCustomer.Id
的FK。
答案 0 :(得分:1)
只需更改
USING MySourceTable AS SOURCE
to
using (select * from MySourceTable where PackageId <> 0) as Source