Inserting new records using trigger

  • I think this maybe a repeat question. How do i insert any new records from table A to table B using triggers? assuming that table A and Table B have same columns.

  • In your FOR INSERT trigger do like this:

    INSERT INTO tblB (ListOfColumns) SELECT ListOfColumns FROM inserted

    The inserted table only exists to triggers to access and they contain the new information going in.

    "Don't roll your eyes at me. I will tape them in place." (Teacher on Boston Public)

  • Thanks for the prompt reply antares. This brings to my second question, how would i update table B with the data being updated on table A?

  • Almost exactly the same FOR UPDATE trigger:

    UPDATE tblB SET tblB.Column = inserted.Column

    FROM inserted

    WHERE tblB.whatiskey = inserted.whatiskey

    You can also check for a specific column updating by using IF UPDATE(<column_name>) or IF COLUMNC_UPDATED see BOL for more deatils. Also if the key item changed you can use the deleted table to handle putting the items together see BOL about the inserted and deleted tables for more detail.

    "Don't roll your eyes at me. I will tape them in place." (Teacher on Boston Public)

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply