批量插入的触发触发器

时间:2010-04-30 06:40:14

标签: sql-server sql-server-2005

ALTER TRIGGER [dbo].[TR_O_SALESMAN_INS]
   ON  [dbo].[O_SALESMAN]
   AFTER INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    DECLARE @SLSMAN_CD NVARCHAR(20)
    DECLARE @SLSMAN_NAME NVARCHAR(20)
    SELECT @SLSMAN_CD = SLSMAN_CD,@SLSMAN_NAME=SLSMAN_NAME
    FROM INSERTED

    IF NOT EXISTS(SELECT * FROM O_SALESMAN_USER WHERE SLSMAN_CD = @SLSMAN_CD)
    BEGIN
        INSERT INTO O_SALESMAN_USER(SLSMAN_CD, PASSWORD, USER_CD)
        VALUES(@SLSMAN_CD, @SLSMAN_CD,@SLSMAN_NAME )
    END
END

这是为table(O_SALESMAN)编写的触发器,用于从中获取少量列并将其插入另一列table(O_SALESMAN_USER)。目前,批量数据通过存储过程插入到O_SALESMAN表中,其中触发器仅被触发一次,并且O_SALESMAN_USER每次执行存储过程时只插入一条记录,i希望触发器在每个和每个插入O_SALESMAN的记录之后运行,这样两个表应该具有相同的计数而不发生..所以请让我知道在这个触发器中可以修改什么来实现相同的... ..

3 个答案:

答案 0 :(得分:7)

您可以按如下方式使用光标:

create trigger trg_insertstuff
on [O_SALESMAN]
after insert
as

  DECLARE @SLSMAN_CD NVARCHAR(20)
    DECLARE @SLSMAN_NAME NVARCHAR(20)


 declare db_cursor CURSOR FOR  
SELECT SLSMAN_CD, SLSMAN_NAME
from inserted

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @SLSMAN_CD , @SLSMAN_NAME 

WHILE @@FETCH_STATUS = 0  
BEGIN  

IF NOT EXISTS(SELECT * FROM O_SALESMAN_USER WHERE SLSMAN_CD = @SLSMAN_CD)
    BEGIN
        INSERT INTO O_SALESMAN_USER(SLSMAN_CD, PASSWORD, USER_CD)
        VALUES(@SLSMAN_CD, @SLSMAN_CD,@SLSMAN_NAME )
    END


FETCH NEXT FROM db_cursor INTO  @SLSMAN_CD , @SLSMAN_NAME 
end

CLOSE db_cursor  
DEALLOCATE db_cursor

答案 1 :(得分:4)

是的,每个语句触发一次,而不是每行一次。

所以你需要这样的东西:

SET NOCOUNT ON

INSERT INTO O_SALESMAN_USER(SLSMAN_CD, PASSWORD, USER_CD)
SELECT
    i.SLSMAN_CD,i.SLSMAN_CD,i.SLSMAN_NAME
FROM
    inserted i
        left join
    O_SALESMAN_USER u
        on
            i.SLSMAN_CD = u.SLSMAN_CD
where
    u.SLSMAN_CD is NULL

答案 2 :(得分:1)

我的场景是,(表名:Stock,StockLog)

我通过存储过程在Stock表中插入批量行,并希望在StockLog表中包含所有这些行

首先,我在Stock表的插入触发器中对你(通过变量)做了同样的事情 但是因为使用

而得到错误
DECLARE @StocklId bigint

SET @StocklId = (SELECT StocklId FROM inserted)

我有多个值(SELECT StocklId FROM inserted),因为我插入多行,然后我删除所有变量, 现在我正在做这个

INSERT INTO StockLog(StocklId,PharmacyId,TransactionDetailId,ProductId,TotalQty,ReservedQty,AvailableQty,strUserName,strTerminalName,strVer)

SELECT StocklId, PharmacyId, TransactionDetailId, ProductId, TotalQty, 0, AvailableQty,strUserName, strTerminalName, strVer FROM inserted

现在一切都很好