如何在插入sql语句中使用FIRE_TRIGGERS
我正在尝试将数据从表“tb_A”复制到其自身(具有不同的主键)。
当“tb_A”表插入新记录时,我编写了一个触发器来用一条记录填充另一个表“tb_B”。
我发表了以下声明。
INSERT INTO [tb_A]
([NAME])
select top (20)[NAME] from [tb_A]
我预计“tb_B”中有 20 条新记录。但我没有。
无论如何,我看到在批量插入期间使用 FIRE_TRIGGERS 来解决这个问题。 有没有办法在插入语句上使用它?请给我提供例子。
Gayan
触发代码(从 Gayan 的评论复制到 gbn 的答案):
CREATE TRIGGER UpdatetbB ON [dbo].[tb_A] FOR INSERT
AS
DECLARE @AID as int
SELECT @AID = [ID] FROM inserted
INSERT INTO [tb_B]([IDA]) VALUES (@AID)
I am trying to copy data from table "tb_A" to itself (with different primary key).
When "tb_A" table is insert new record, I have written a trigger to populate another table "tb_B" with one record.
I ran the following statement.
INSERT INTO [tb_A]
([NAME])
select top (20)[NAME] from [tb_A]
I was expected 20 new records in "tb_B". But I didn't.
Anyway I saw FIRE_TRIGGERS is using during bulk insert to overcome this issue.
is there is a any way to use it on inset statements too ? Please provide me example.
Gayan
Trigger code (copied from Gayan's comment to gbn's answer):
CREATE TRIGGER UpdatetbB ON [dbo].[tb_A] FOR INSERT
AS
DECLARE @AID as int
SELECT @AID = [ID] FROM inserted
INSERT INTO [tb_B]([IDA]) VALUES (@AID)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的触发器无法正常工作的原因是它设计不当。即使您要插入一百万条记录,每次插入都会触发一次触发器。您有一个触发器,假设它将一次处理一条记录。每当您将插入或删除的值形式设置为标量变量时,触发器都是错误的,需要重写。尝试这样的事情。
The reason your trigger did not work properly is because it is poorly designed. Triggers fire once for each insert even if you are inserting a million records. You havea trigger that makes the assumption it will owrk one record at a time. Anytime you set a value form inserted or deleted to a scalar variable the trigger is wrong and needs to be rewritten. Try something like this instead.
FIRE_TRIGGERS 仅适用于 BULK INSERT (和 bcp),而不是“标准”INSERT
我希望您的触发器看起来像
您使用特殊的 INSERTED 表来获取 tb_A 中的新行列表,然后从该表插入到 tb_B 中。这适用于多行
如果您添加触发代码,那么我们可以解释出了什么问题。
编辑:您的触发器只会从 INSERTED 读取一行(任何行,没有特定顺序)。它不像我的粗略示例那样基于设置。
FIRE_TRIGGERS is only for BULK INSERT (and bcp), not "standard" INSERT
I'd expect your trigger to look something like
You use the special INSERTED table to get the list of new rows in tb_A, then INSERT from this into tb_B. This works for more than one row
If you add the trigger code then we can explain what went wrong.
Edit: your trigger will only read a single row (any row, no particular order) from INSERTED. It isn't set based like my rough example.