请用SQL语言帮我解决触发器。
我有2个表product_subcategories
和Products
。
product_subcategories
:id, name, count_products
Products
:id, name, price, id_product_subcategories
在产品表中添加或删除行以更新子类别中的产品数量时是必要的
例如,我们有两个子类别" name = first,count_products = 0"," name = second,count_products = 0"。当添加到产品表3行时:" name = pr1,price = 1,id_product_subcategories = 1"," name = np2,price = 2,id_product_subcategories = 1",&#34 ; name = PR3,price = 5,id_product_subcategories = 2"
表子类别应该是
" name = first,count_products = 2"," name = second,count_products = 1"
这是我写的内容,但由于某种原因,他不会在一行中工作,而且我不明白该怎么做,当你在插入的表中添加几行作为遍历每一行时?
CREATE TRIGGER
countproductscategories
ON
dbo.products
AFTER
INSERT
AS
IF @@ROWCOUNT = 1
BEGIN
UPDATE dbo.product_subcategories
SET count_products = count_products + 1
WHERE dbo.product_subcategories.id = (SELECT id FROM inserted)
END;
答案 0 :(得分:1)
什么是@@ROWCOUNT = 1
?这应该做你想要的:
CREATE TRIGGER
countproductscategories
ON dbo.products AFTER INSERT
AS
BEGIN
UPDATE dbo.product_subcategories
SET count_products = count_products + 1
WHERE dbo.product_subcategories.id IN (SELECT id FROM inserted)
END;
如果您只想在插入一行时执行此操作,则可以执行以下操作:
CREATE TRIGGER
countproductscategories
ON dbo.products AFTER INSERT
AS
BEGIN
UPDATE dbo.product_subcategories
SET count_products = count_products + 1
WHERE dbo.product_subcategories.id IN (SELECT id FROM inserted) AND
(SELECT COUNT(*) FROM inserted) = 1;
END;