-1

有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

then: 触发器,它为 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 中添加(和求和)触发器

4

1 回答 1

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
于 2012-08-24T01:56:02.957 回答