SQL Server多行插入触发器

时间:2017-11-20 16:23:15

标签: sql sql-server triggers bulkinsert multirow

我已测试过该触发器,但它仅适用于一个插入行。

触发器因多行插入而失败,我没有找到修复触发器的语法。

有任何修复建议吗?

感谢stackoverflow用户让我注意到这个问题。

USE [MY_DB]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[tr_update_father]
   ON [dbo].[PROD_IVR_CALL]
   AFTER INSERT
AS 
BEGIN

    SET NOCOUNT ON;

    DECLARE @tnumber nvarchar(50), @id_inserted int, @id_prod_file int;

         select 
         @id_inserted = ins.id,
         @tnumber = ins.tnumber ,
         @id_prod_file = pf.ID_PROD_FILE
         from inserted ins
         inner join prod_failure pf on (ins.ID_PROD_FAILURE = pf.ID);    

    update prod_ivr_call
    set id_father = sq.ID
    from
        (select min(pic.id) as ID
        from prod_ivr_call pic
        inner join prod_failure pf on (pic.ID_PROD_FAILURE = pf.ID)
        where pic.tnumber = @tnumber 
        and pic.is_requested = 0
        and pf.ID_PROD_FILE = @id_prod_file
        group by pic.tnumber ) sq

END

1 个答案:

答案 0 :(得分:1)

您的UPDATE语句在语法上不正确。您实际上可以使用CTE合并触发器的两个语句,然后对此UPDATE执行CTE

ALTER TRIGGER [dbo].[tr_update_father]
   ON [dbo].[PROD_IVR_CALL]
   AFTER INSERT
AS 
BEGIN

    SET NOCOUNT ON;

    ;WITH ToUpdate AS (
        SELECT pic.id_father,
               MIN(pic.id) OVER (PARTITION BY pic.tnumber) AS min_id
        FROM prod_ivr_call pic
        INNER JOIN join prod_failure pf ON pic.ID_PROD_FAILURE = pf.ID
        JOIN inserted ins ON ins.ID_PROD_FAILURE = pf.ID
        WHERE pic.tnumber = ins.tnumber AND pic.is_requested = 0
     )
     UPDATE ToUpdate
     SET id_father = min_id

END