views:

65

answers:

2

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.

+5  A: 

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.

LittleBobbyTables
+5  A: 

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

Raj More
One other thing it is important to mention is that triggers in SQL Server operate once per insert and if you insert a group of records must be able to handle that. This code does that, but I wanted the person who asked the question to understand why to use set-based logic and not try to set things to a variable and use the values clause. Also, always test a trigger by doing a multi-row insert update or delete.
HLGEM
Excellent answer, thanks so much for the help and insight.