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.
October 22, 2002
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.
About the Author
You May Also Like