Wednesday, March 21, 2012

Insert Trigger

I have a table that has a unique ID field. When a new record is inserted into the table I would like to insert the ID into 3 other tables. I am new to triggers and am not sure how to handle this. Any idea how the trigger would be written?

I don't have a server around at the moment to provide you with working code, but all in all you have to create an AFTER INSERT trigger that will insert value inserted.ID (inserted is a system name of result set that holds everything that user inserted into the main table) to other 3 tables.

Feel free to ask if you still have trouble with this.

|||

Hi,

keep in mind that the insert trigger will be always fired once per statement not per row. So getting you Id won′t work if you put it in a variable or something like this, a pseudotrigger for you could be something like

CREATE TRIGGER SomeTrigger
ON SOMETable
FOR INSERT
AS
BEGIN

INSERT INTO FirstTable(Columnlist,Othercolumns)
SELECT ID, Othercolumns FROM Inserted


INSERT INTO SecondTable(Columnlist,Othercolumns)
SELECT ID, Othercolumns FROM Inserted

INSERT INTO ThirdTable(Columnlist,Othercolumns)
SELECT ID, Othercolumns FROM Inserted

END

HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

No comments:

Post a Comment