提前抱歉我的英文,问题是:因为我无法考虑触发器的逻辑,底线是有2个表:
当将记录添加到教区杂志中的表时,应操作一个触发器,检查表是否为空添加新条目(材料,库存数量),如果表有记录,则在条件下更新它们Material = (select the part Name From inserted)
,但如果表中有记录并Material != select the part Name From inserted)
,则添加新记录。
以下是触发器的代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Trigger [dbo].[Application Log Sheet]
ON [dbo].[Parish magazine]
FOR INSERT
AS
DECLARE @a INT;
DECLARE @b int;
SELECT @a = COUNT(*)
FROM Bill of materials
IF @a > 0
BEGIN
UPDATE Vedomostithe
SET Kolichestvennogo = the Number of stock + (select Quantity from inserted)
WHERE Material = (select the part Name from inserted)
END
ELSE IF @a >= 0
INSERT INTO Bill of material(Material, Quantity in stock)
SELECT the part Name, Number
FROM the arrival Journal
WHERE [ID] IN (SELECT [ID] FROM inserted)
表材料清单:
create table Bill of materials
(
ID int primary key,
Material nvarchar(max),
Quantity in stock int
)
表到期日记:
create table Journal of the parish
(
ID int primary key,
Part name nvarchar(max),
The number of int
)
答案 0 :(得分:1)
一方面,您不应该存储可以计算的数据,因为所有这一切都为您提供了存储计算的机会与其他数据不一致。因此,我通常建议只有一个显示总数的视图。
另一方面,这看起来像是MERGE
的简单任务。但我们需要记住,inserted
可以包含多个行,这些行可以用于多个不同的部分。所以,我们想要这样的东西:
ALTER Trigger [dbo].[Application Log Sheet]
ON [dbo].[Parish magazine]
for insert
AS
MERGE INTO [Bill of Materials] t
USING (SELECT PART, SUM(Quantity) as Qty from inserted group by PART) s
ON t.Part = s.Part
WHEN MATCHED THEN UPDATE SET Quantity = t.Quantity + s.Qty
WHEN NOT MATCHED THEN INSERT (Part,Quantity) VALUES (s.Part,s.Qty)
道歉,如果上面的一些名称不正确,但希望你能看到如何调整它以满足你的要求(你的问题似乎在各种表/列名称之间翻转,这样似乎有四个不同的表名字,而你开始提问时有两个。)