If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > Microsoft SQL Server > Stored Proc insert - multiple tables

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 01-26-12, 13:52
Rebecca Johnston Rebecca Johnston is offline
Registered User
 
Join Date: Oct 2008
Posts: 54
Stored Proc insert - multiple tables

Hi,
Any suggestion on how to insert data into 2 tables in a stored proc.
Scenario is:

Table 1 insert is generated and the primary key is created. This key is an identity column and is the only thing that makes the row unique.

Table 2 needs an insert but one of the columns that is needed is the newly created column 1 primary key.

How do I know what the new rows primary key value is from Table 1?


Thanks in advance,
Rebecca
Reply With Quote
  #2 (permalink)  
Old 01-26-12, 14:46
MCrowley MCrowley is offline
Wage drone 24601
 
Join Date: Jan 2003
Location: Massachusetts
Posts: 4,899
Use the SCOPE_IDENTITY() function.
Reply With Quote
  #3 (permalink)  
Old 01-26-12, 15:24
blindman blindman is online now
World Class Flame Warrior
 
Join Date: Jun 2003
Location: Ohio
Posts: 11,736
That won't work unless she is only inserted one record at a time.

Rebecca, your data should have a "natural" key in addition to the "surrogate" key you are creating. The natural key is a column of combination of columns inherent in the data which uniquely identify each record. You can use the natural key to look up the newly created surrogate keys in your first table.
__________________
If it's not practically useful, then it's practically useless.

blindman
www.chess.com: "sqlblindman"
Reply With Quote
  #4 (permalink)  
Old 01-26-12, 15:36
MCrowley MCrowley is offline
Wage drone 24601
 
Join Date: Jan 2003
Location: Massachusetts
Posts: 4,899
If there are multiple inserts (it's not really specified here), she can see if the OUTPUT clause of the INSERT statement will work for her. That may only work if Table1 has a natural or other unique key that she can map the identity column to.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On