Inserting Records into Two Tables at Once

You can effectively streamline your INSERT operation by adding records to two tables at the same time, but there’s one pitfall you should watch out for.

1 Min Read
ITPro Today logo in a gray background | ITPro Today


How can I use one INSERT statement and an INSERT trigger to add records to two tables at the same time?

To add records to two tables at the same time, you need to direct your INSERT statement at the first table. Then, on that table, create an INSERT trigger that uses the inserted table to add records to the second table. Listing 3 shows sample code that performs these operations.

The most important tip to remember about writing this statement is that inserting records into one table, activating the INSERT trigger, and adding records to a second table take place in the same transaction and at the same isolation level. Therefore, you need to avoid creating a long-running trigger that delays your users. Note that this answer assumes that the two tables sustain a data relationship. Otherwise, wrapping two separate INSERT statements in a transaction would be more efficient.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like