0

我在一张类似这样的表上有一个触发器:

ALTER TRIGGER [shoot_sms] 
  ON  [dbo].[MyTable]
 AFTER  INSERT
AS
begin
declare @number bigint
declare @body varchar(50)
declare @flag int

select @number=number,@body=body,@flag=flag from inserted

if(@flag=0)
begin

insert into temptable (number,body,status)
select @number,@body,'P'

end
end

现在我在 mytable 中创建两个条目,如下所示:

insert into mytable(number, body, flag)
values(3018440225, 'This is test', 0)

insert into mytable(number, body, flag)
values(3018440225, 'This is test', 0)

我一次执行这些查询,但是对于这两个查询,触发器只触发一次,并且只为第一个查询执行任务。

如何使它适用于两个插入语句?

4

2 回答 2

2

只是一个想法,但在这两个插入语句之间放置一个 GO 语句,这可能会导致触发器触发两次。

我认为您可能应该重写触发器以处理多行插入。

这是您转换的查询。你现在应该得到两行。

ALTER TRIGGER [shoot_sms] 
  ON  [dbo].[MyTable]
 AFTER  INSERT
AS
begin


insert into temptable (number,body,status)
select number,body,'P'
from inserted
where flag = 0

end

另请注意,您的触发器现在要简单得多。

于 2013-02-16T06:39:43.017 回答
1

Since those two statements are in one SQL batch, the trigger will (by design) only fire once.

Triggers don't fire once per row - they fire once per statement! So if you have an INSERT or UPDATE statement that affects more than one row, your trigger will have more than one row in the Inserted (and possibly Deleted) pseudo tables.

The way you wrote this trigger is really not taking into account that Inserted could contain multiple rows - what row do you select from the Inserted table if you're inserting 20 rows at once?

select @number = number, @body = body, @flag = flag from inserted

You need to change your trigger to take that into account!

于 2013-02-16T08:16:25.500 回答