简体   繁体   中英

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).

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)

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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