SQL触发器和复合键

时间:2011-12-21 11:12:30

标签: sql-server

我正在为表创建一个触发器,我有以下声明:

UPDATE [dbo].ConsignmentTripBreakdown SET VehicleTypeID = CONVERT(bigint,LTRIM(RTRIM(VehicleType)))
WHERE [dbo].ConsignmentTripBreakdown.ID IN (SELECT ID FROM Inserted)

问题是,ConsignmentTripBreakdown上没有'ID'字段 - 而是在3个字段上有一个复合键。我将如何为此修改where子句?

2 个答案:

答案 0 :(得分:4)

UPDATE
  [dbo].ConsignmentTripBreakdown
SET
  VehicleTypeID = CONVERT(bigint,LTRIM(RTRIM(inserted.VehicleType)))
FROM
  [dbo].ConsignmentTripBreakdown
INNER JOIN
  inserted
    ON  inserted.pk_part1 = ConsignmentTripBreakdown.pk_part1
    AND inserted.pk_part2 = ConsignmentTripBreakdown.pk_part2
    AND inserted.pk_part3 = ConsignmentTripBreakdown.pk_part3

答案 1 :(得分:1)

在复合键的所有组件列上使用连接到inserted表。例如:

UPDATE ctb
SET ctb.VehicleTypeID = CONVERT(bigint,LTRIM(RTRIM(VehicleType)))
FROM  [dbo].ConsignmentTripBreakdown ctb
INNER JOIN Inserted i ON i.k1 = ctb.k1 and i.k2 = ctb.k2 and i.k3 = ctb.k3