SQL Server trigger on insert and how to reference

2019-02-24 20:27发布

问题:

High level I have two tables that need to have some of the data mirrored. I can't go through and change all of the code to write to both so I thought I'd use a SQL trigger to insert data into the 2nd table anytime data is inserted into the 1st. Here is where I am stuck:

CREATE TRIGGER new_trigger_INSERT
ON old_table
FOR INSERT
INSERT INTO new_table (id, first_name, last_name)
VALUES () --This is where I'm lost, I need to insert some of the data from the insert that executed this trigger

Any help is appreciated, also if there is a better way to accomplish this let me know.

回答1:

Use the 'inserted' table:

CREATE TRIGGER new_trigger_INSERT 
ON old_table 
FOR INSERT 
INSERT INTO new_table (id, first_name, last_name) 
SELECT col1, col2, col3 FROM inserted

[PS: Don't forget to ensure your triggers handle multiple rows...]

Ref. Create Trigger

Good article: Exploring SQL Server Triggers



回答2:

In the triggers you have "inserted" and "deleted" tables. In this case you only use the "inserted" table, but in update trigger you use both.