question

anonym123 avatar image
anonym123 asked

UPDATING OF A TABLE AFTER INSERTING A ROW INTO ANOTHER TABLE

iF I insert into a table and if i want to update another table with the primary key in the first table as the foreign key int the 2nd table?
updateforeign-key
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Håkan Winther avatar image
Håkan Winther answered
You didn't mention the SQL server version you are using, but I assume it is SQL server 2005 or later as the previous versions have passed mainstream and extended support from Microsoft. I would recommend the output clause.[ http://msdn.microsoft.com/en-us/library/ms177564.aspx][1] I give you a short sample to get you started. DECLARE @tmp TABLE( myID INT, someOtherColum INT --something to identify the rows in second table ) INSERT INTO table1 (col1, col2) OUTPUT INSERTED.myID, col2 INTO @tmp (myID, someOtherColumn) SELECT 1 AS col1, 2 AS col12 UPDATE table2 SET myFK FROM table2 t2 INNER JOIN @tmp t ON t2.pkcolumn = t.someOtherColum [1]: http://msdn.microsoft.com/en-us/library/ms177564.aspx
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Grant Fritchey avatar image Grant Fritchey ♦♦ commented ·
Absolutely the best method out there because it supports more than one row. Anything else is a design compromise that you'll pay for down the road.
0 Likes 0 ·
Håkan Winther avatar image Håkan Winther commented ·
It would be even better if you have SQL 2008 and can replace the UPDATE with a MERGE statement instead. (I have seen some terrible UPDATE statements that can give unpredictable results)
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.