对触发器感到困惑:我有两种类型的记录,'L'库和'N'正常。当更新或插入'N'时,我需要更新相应的'L'。 “L”记录的更新不应自行更新。 此代码不允许更新成功。为什么?
ALTER trigger updateProductLibrary
on Product
after update as
BEGIN
-- either deleted (old) or inserted (new)
declare @counter int, @insertedType char(1)
set @insertedType = 'Z'
select @insertedType = i.type
from inserted i
if( @insertedType = 'N')
begin
select @counter = count(*)
from product p join inserted i on
p.sku = i.sku and
p.type = 'L' -- for library
if( @counter > 0) -- update
BEGIN
update p set name = i.name
from product p join inserted i on
p.sku = i.sku and
p.type = 'L'
END
ELSE -- insert
BEGIN
insert into product (sku, name, type)
select i.sku, i.name, 'L'
from inserted i
END
END
END
答案 0 :(得分:1)
您的基本错误是您似乎希望每行调用一次此触发器。这是 NOT 的情况 - 每批次都会调用一次。
所以这里的陈述很多次都不会起作用:
select @insertedType = i.type
from inserted i
如果您的inserted
伪表中有10个条目
您需要重写触发器,以考虑inserted
表可以包含多行!
答案 1 :(得分:1)
您的触发器需要支持每次更新多行。
ALTER TRIGGER updateProductLibrary ON dbo.Product AFTER UPDATE
AS
BEGIN
UPDATE p
SET name = i.name
FROM inserted i
INNER JOIN dbo.Product p
ON p.sku = i.sku
AND p.type = 'L'
WHERE i.type = 'N'
INSERT INTO product (sku, name, type)
SELECT i.sku, i.name, 'L'
FROM inserted i
WHERE i.type = 'N'
AND i.sku NOT IN
(SELECT p.sku
FROM dbo.Product p
WHERE p.type = 'L')
END