如何重写此触发器以使用游标或基于集合的方法?

时间:2014-06-10 17:09:26

标签: sql-server tsql triggers cursor

当为产品更新Product OrderNo时,以下触发器应该从ProductOrders表中删除行。这在前端工作正常,但如果有人在后端进行大规模更新(更新多个订单号),我需要一种方法来为所有产品订单更新运行此触发器。

CREATE TRIGGER [trgAfterOrderNoUpdate] ON [Products]
    FOR UPDATE
AS 

DECLARE @id uniqueidentifier

SELECT @id = i.ID
FROM inserted i

if UPDATE(OrderNo)
DELETE FROM ProductOrders
WHERE ID= @id

3 个答案:

答案 0 :(得分:2)

试试这个:

DELETE PO
FROM ProductOrders PO
INNER JOIN INSERTED I
    ON PO.ID = I.ID
INNER JOIN DELETED D
    ON PO.ID = D.ID
WHERE I.OrderNo <> D.OrderNo
OR (I.OrderNo IS NULL AND D.OrderNo IS NOT NULL)
OR (I.OrderNo IS NOT NULL AND D.OrderNo IS NULL)

答案 1 :(得分:1)

使用触发器时请记住,插入或删除的项目是表格而不是单行。您需要加入插入的表以删除正确的行

CREATE TRIGGER [trgAfterOrderNoUpdate] ON [Products]
    FOR UPDATE
AS 


DELETE FROM ProductOrders
WHERE ID in (select ID 
             from    inserted i
                  inner join Products p on i.Id = p.ID
             where i.OrderNo != p.OrderNo)

答案 2 :(得分:1)

听起来你真的想用ON DELETE CASCADE

来使用外键

Technet: Cascading Referential Integrity Constraints

Technet: Triggers Compared to Constraints

如果你真的需要使用触发器,那么你需要这样的东西:

DELETE po
FROM ProductOrders po
INNER JOIN (
  SELECT id, OrderNo FROM deleted
  EXCEPT
  SELECT id, OrderNo FROM inserted
) i ON i.id = po.id