共有3个表格:
Suppl, fields: (Code_name, Tasknum, Pki_num, Group_eng, Name, Descr, Cost, Quan, shop)
Maker, fields : (Code_maker, Code_maker_arch, Code_name, provider)
Arrival, fields: (Code_arr, Code_maker, quan_arr)
我需要获取一个表(用于导出到Excel),例如update_501(Group_eng,Name,Descr,quan_arr),它将包含group_eng_501的唯一“Descr”。字段“quan_arr”需要保留每个唯一“Descr”表Arrival.quan_arr中字段的总和。
第一
Insert dbo.update_501(Group_eng, Name, Descr)
select Group_eng, Name, Descr
from Suppl
where (Group_eng = 501)
group by Group_eng, Name, Descr
然后: 触发器,为update_501添加唯一的“descr”
ALTER trigger [update_pki_501] ON [dbo].[Suppl]
After Insert
as
begin
Set nocount on;
if (not(exists(select * from [INSERTED])))
return;
Insert dbo.update_501(Group_eng, Name, Descr)
select I.Name
,I.Descr
,I.Group_eng
from Inserted I
where (I.Group_eng = 501)
and not exists(select * from dbo.update_501 x where x.Group_eng=I.Group_eng and x.Descr = I.Descr)
end
请帮助一个触发器,它将在Arrival.quan_arr的update_501.quan_arr中添加(和求和)
答案 0 :(得分:0)
我很好奇为什么你不想在插入表格时计算总和,因为你的触发器仅用于插入。
大概你可以
INSERT update_501 (Group_eng, Name, Descr, quan_arr)
SELECT s.Group_eng, s.Name, s.Descr, Sum(a.Quan_Arr)
FROM Suppl s
JOIN Maker m ON s.Code_Name = m.Code_Name
JOIN Arrival a ON m.Code_Maker = a.Code_Maker
WHERE -- if a where clause is needed
GROUP BY s.Group_eng, s.Name, s.Descr
--HAVING --if a having clause is appropriate
插入后,如果要在插入新的Arrival时更新它,那么您需要一个针对Arrival表的插入触发器,如下所示:
CREATE TRIGGER trg_Arrival_update_501 ON dbo.Arrival
AFTER INSERT
AS Begin
Set nocount on;
if (not(exists(select * from Inserted)))
return;
DECLARE @Group_eng <datatype>,
@Name <datatype?,
@Descr <datatype>;
DECLARE @tbl table (
Group_Eng <datatype>,
Name <datatype>,
Descr <datatype>
);
INSERT @tbl
SELECT s.Group_Eng, s.Name, s.Descr
FROM Suppl s
JOIN Maker m ON s.Code_Name = m.Code_Name
JOIN Inserted i ON m.Code_Maker = i.Code_Maker;
UPDATE u
SET quan_arr = newTotal.quan_sum
FROM update_501 u
JOIN @tbl t ON u.Group_Eng = t.Group_Eng AND u.Name = t.Name AND u.Descr = t.Descr
JOIN Suppl s ON u.Group_Eng = s.Group_Eng
JOIN (
SELECT m.Code_Name, Sum(a.quan_arr) as quan_sum
FROM Maker m JOIN Arrival a ON m.Code_Maker = a.Code_Maker
) newTotal;
END
注意:我可能误解了你们桌子之间的连接。如果您将表格结构转换为易于理解的问题命名,它将帮助您获得更好的答案。例如
Suppl (Suppl_ID, ...)
Maker (Maker_ID, ..., Suppl_ID)
etc