SQL 服务器插入触发器插入不止一次

SQL Server Insert trigger inserting more than once

我的触发器不知为何插入了4次,最后一次只被分组。基本上我想要做的是当信息被插入我的 table tbl_delete_Panel 我想对这些数据进行分组并将分组插入 tbl_delete_panel_Orderin.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Trigger[dbo].[deletePanelSQL]
ON [dbo].[tbl_delete_Panel]
AFTER INSERT
AS
BEGIN
     /* Insert Summed Quantity for each stud or track into tbl_delete_panel for deletion. tbl_delete_panel trigger will be triggered */
    INSERT INTO tbl_delete_panel_Orderin (Part_Name, OrderID, SumOfQTY)
       SELECT 
           tbl_delete_panel.Part_Name, tbl_delete_panel.OrderID, 
           Sum(tbl_delete_panel.QTY) AS SumOfQTY
       FROM 
           tbl_delete_panel
       GROUP BY 
           tbl_delete_panel.Part_Name, tbl_delete_panel.OrderID;
END;

现在,每次触发此触发器时,您都会从 tbl_delete_panel 中插入 完整行集

应该做的 是查看 Inserted 伪 table ,其中 可以并且将包含多行 (所以你需要处理这种情况,用一个很好的,适当的 基于集合的方法 - 没有游标,没有 while 循环!) - 并插入那些行(由导致触发器触发的语句) - 不是整个 table 每次 !

尝试这样的事情:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Trigger[dbo].[deletePanelSQL]
ON [dbo].[tbl_delete_Panel]
AFTER INSERT
AS
BEGIN
     /* Insert summed quantity for each stud or track into tbl_delete_panel for deletion. tbl_delete_panel trigger will be triggered */
    INSERT INTO tbl_delete_panel_Orderin (Part_Name, OrderID, SumOfQTY)
       SELECT 
           Part_Name, OrderID, 
           Sum(QTY) AS SumOfQTY
       FROM 
           Inserted i
       GROUP BY 
           Part_Name, OrderID;
END;