我想在插入多个值时触发触发器,即使它们像这样重复:
假设值为0(表1):
插入上面的值(在创建触发器时)应该给我们:
但它的工作正常,如果买的价值是99,那么" Prod1"例如,我跑:
关于Prod2,由于Prod1有一个约束错误,它根本没有更新,因为它有一个约束错误。
答案 0 :(得分:3)
UPDATE T1
SET Bought = IIF((Bought + uc.UpdCount) < 100, Bought + uc.UpdCount, 100)
FROM TABLE_1 T1
JOIN (
SELECT ProdName, COUNT(*) as UpdCount
FROM Inserted
GROUP BY ProdName
) uc ON uc.Name = T1.ProdName
WHERE T1.Bought < 100;
使用MERGE语句进行upsert,它看起来像这样:
MERGE TABLE_1 AS t
USING (
SELECT ProdName, COUNT(*) as UpdCount
FROM Inserted
GROUP BY ProdName
) AS s (Name, UpdCount) ON (t.ProdName = s.Name)
WHEN MATCHED THEN
UPDATE SET Bought = IIF((t.Bought + s.UpdCount) < 100, t.Bought + s.UpdCount, 100)
WHEN NOT MATCHED THEN
INSERT (ProdName, Bought) VALUES (s.Name, IIF(s.UpdCount < 100, s.UpdCount, 100));