Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Insert to Parent/Child tables Expand / Collapse
Author
Message
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: Monday, June 30, 2014 12:49 PM
Points: 318, Visits: 440
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?



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


SSC-Insane

SSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-Insane

Group: General Forum Members
Last Login: Today @ 6:21 PM
Points: 23,081, Visits: 31,619
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


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Today @ 6:48 AM
Points: 7,094, Visits: 12,581
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