how to work with after insert trigger in sql server 2008

24,978

Solution 1

create trigger tri_inserts on a
after insert
as
set nocount on

insert into b (id, name)
    SELECT id, name FROM INSERTED
GO

Solution 2

@gbn has the best solution, but I want you to understand why the SELECT clause is better than using a VALUES clause in a trigger. Triggers fire for each batch of records inserted/updated/deleted. So the inserted pseudotable or the deleted pseudotable may have one record or they may have a million. The trigger has to be able able to handle either case. If you use a values clause, you only get the action happening for one of the records out the the million. This casues data integrity issues. If you decide to loop through the records in a cursor and use the VALUES clause, your performance will be horrible when you get a large number of records. When I came to this job, we had one such trigger, it took 45 minutes to insert a 40,000 record insert. Removing the cursor and using a set-based solution based on athe SELECT clause (Although a much more complex one than the example)reduced the time for the same insert to around 40 seconds.

Share:
24,978
Abbas
Author by

Abbas

Updated on January 28, 2020

Comments

  • Abbas
    Abbas about 4 years

    i am working on sql server, where i want to insert the record in a particular table say (a), this table contains two column [id (Identity Field) and name(nvarchar(max)] now after the records is inserted in table (a), a trigger should fire and insert the identity field value in table b.... i am using after insert trigger for this purpose but i am not getting how i would be getting the identity field value in trigger... which should be inserted in table b.

    This is what i am using

    create trigger tri_inserts on (a)
    after insert
    as
    begin
       insert into b (id, name) values (?,?)
    end
    

    Please reply as soon as possible.. Thanks and Regards Abbas Electricwala