简体   繁体   English

如何在插入SQL语句中使用FIRE_TRIGGERS

[英]How to Use FIRE_TRIGGERS in insert sql statement

I am trying to copy data from table "tb_A" to itself (with different primary key). 我正在尝试将数据从表“ tb_A”复制到自身(使用不同的主键)。

When "tb_A" table is insert new record, I have written a trigger to populate another table "tb_B" with one record. 当“ tb_A”表插入新记录时,我编写了一个触发器,用一条记录填充另一个表“ tb_B”。

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". 预计“ tb_B”中有20条新记录。 But I didn't. 但是我没有。

Anyway I saw FIRE_TRIGGERS is using during bulk insert to overcome this issue. 无论如何,我看到在批量插入过程中正在使用FIRE_TRIGGERS来解决此问题。 is there is a any way to use it on inset statements too ? 有没有办法在inset语句上使用它? Please provide me example. 请提供我的例子。

Gayan 加扬


Trigger code (copied from Gayan's comment to gbn's answer): 触发代码(从盖安的评论复制到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)

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. 尝试这样的事情。

CREATE TRIGGER UpdatetbB ON [dbo].[tb_A] FOR INSERT 
AS 

    INSERT INTO [tb_B]([IDA])
    SELECT  [ID] FROM inserted 

FIRE_TRIGGERS is only for BULK INSERT (and bcp), not "standard" INSERT FIRE_TRIGGERS仅适用于BULK INSERT(和bcp),不适用于“标准” INSERT

I'd expect your trigger to look something like 我希望您的触发器看起来像

CREATE TRIGGER TRG_tbA_I ON tb_A FOR INSERT
AS
SET NOCOUNT ON

INSERT tb_B (col1, col2, ...)
SELECT col1, col2, ... FROM INSERTED
GO

You use the special INSERTED table to get the list of new rows in tb_A, then INSERT from this into tb_B. 您可以使用特殊的INSERTED表来获取tb_A中新行的列表,然后从该表中将其插入到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. 编辑:您的触发器将只从INSERTED中读取一行(任何行,没有特定的顺序)。 It isn't set based like my rough example. 它没有像我的粗略示例那样设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM