Click here to monitor SSC
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in
Home       Members    Calendar    Who's On

Add to briefcase

Insert to Parent/Child tables Expand / Collapse
Posted Saturday, March 2, 2013 9:34 AM

Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Wednesday, May 11, 2016 4:27 PM
Points: 344, Visits: 444
I have a Parent table (Identity PK with 600,000+ rows) and a child table (with maybe 20,000 rows). The parent and child share the same PK (1 to {0 or 1} relationship). This was done (in hindsight I shouldn't have...) because the child table population is sparse.

I have some new adds to the table in a "flattened" version...that is, the child contents are part of the parent row.

I want to insert the new additions to the Parent/Child table, but I won't know the PK on the parent until the parent row is inserted. How does one accomplish this?

Post #1425866
Posted Saturday, March 2, 2013 11:50 AM



Group: General Forum Members
Last Login: Yesterday @ 9:26 PM
Points: 23,522, Visits: 37,753
Look at using the OUTPUT clause when inserting the parent records to capture the information you need to insert the child records.

Hard to give more with so little information to work with here.

Lynn Pettis

For better assistance in answering your questions, click here
For tips to get better help with Performance Problems, click here
For Running Totals and its variations, click here or when working with partitioned tables
For more about Tally Tables, click here
For more about Cross Tabs and Pivots, click here and here
Managing Transaction Logs

SQL Musings from the Desert Fountain Valley SQL (My Mirror Blog)
Post #1425878
Posted Saturday, March 2, 2013 11:53 AM



Group: General Forum Members
Last Login: Today @ 2:36 AM
Points: 7,933, Visits: 14,357
I am assuming the PK on the parent is an IDENTITY column? In those cases I use an OUTPUT clause on the INSERT...SELECT to capture the new IDENTITY value for each inserted parent row, plus any "key column(s)" that uniquely identify the row in my source table, to a temporary table. Then I can join the temporary table to my source table on the "key column(s)" to do an INSERT...SELECT into the child table, also providing the IDENTITY value on each row in the temporary table.

There are no special teachers of virtue, because virtue is taught by the whole community. --Plato
Post #1425879
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse