Bryan V
Bryan V

Reputation: 537

Insert from table1 to table2 on insert trigger

I'm very new to SQL so forgive my ineptitude.

I'm trying to write a trigger that, on insert to table 1, inserts that record into table 2.

table 1 is [rps_lab_dev].[dbo].[Lab_Employee_Time_Off]

table 2 is [dbo].[Lab_Employee_Time_Off_Detail]

CREATE TRIGGER updatetrig
ON [rps_lab_dev].[dbo].[Lab_Employee_Time_Off]

FOR INSERT

AS
...

I'm unsure about where to go from here (if this is even correct, I don't have sql to check right now).Any direction would be greatly appreciated.

Upvotes: 2

Views: 541

Answers (2)

Raj More
Raj More

Reputation: 48048

While you are in a trigger for an INSERT, then you get a set of records called INSERTED. You can use this to perform any actions that you want.

If you are in the trigger for an UPDATE, then you get two sets of data DELETED and INSERTED - logically where the DELETED is the old data that is going to be overwritten by the new INSERTED data.

In your case, let's do a couple of things here. First off, it is an INSERT trigger, so let's call it that. Then let's get the data from INSERTED (which will have the same column names as your incoming data) and use that to insert into your details table

CREATE TRIGGER Lab_Employee_Time_Off_InsertAction
ON [rps_lab_dev].[dbo].[Lab_Employee_Time_Off]

FOR INSERT

AS


INSERT INTO [dbo].[Lab_Employee_Time_Off_Detail] (Col01, Col02, Col03)
SELECT Col1, Col2, Col3
FROM Inserted

GO

http://msdn.microsoft.com/en-us/library/ms189799.aspx

Upvotes: 5

For SQL Server...

CREATE TRIGGER updatetrig 
ON [rps_lab_dev].[dbo].[Lab_Employee_Time_Off] 

FOR INSERT 

AS 

INSERT INTO [dbo].[Lab_Employee_Time_Off_Detail] (Column1, Column2, Column3)
SELECT Column1, Column2, Column3 FROM inserted

Just replace Column1, Column2 and Column3 with your column names.

Upvotes: 5

Related Questions