Solved

SQL How do I INSERT INTO two tables at once and pass the ID from the first to the second

Posted on 2015-02-20
5
3,747 Views
Last Modified: 2015-02-20
--
-- Two tables w two colums
-- Table "TestContacts", Colums "ContactID", "Name"
-- Table "TestAddress", Colums "ContactID", "Address"
-- Procedure to receive two params
--      INSERT INTO TestContacts.Name
--   ?get the ContactID of the inserted row
--  1. INSERT INTO TestAddress "ContactID, then INSERT INTO the TestAddress "Address" Where ContactID's match
--    or  
--  2. INSERT INTO TestAddress "the ContactID from TestContacts INSERT OPERATION above to ContactID" and "Address"
--    or??
-- result is to have ContactID in each table join(able) and get the right Name and Adress
--  
--         

CREATE PROCEDURE [dbo].[TestAddContact]
      (
      @Name nvarchar(50)
      ,@Address nvarchar (50)
      )
AS
BEGIN
      declare @IdentityValue int
      
INSERT INTO dbo.TestContacts ([Name])
OUTPUT INSERTED.ContactID INTO dbo.TestAddress([ContactID])
VALUES (@Name)

INSERT INTO dbo.TestAddress ([Address])
VALUES (@Address)
WHERE ContactID = INSERTED.ContactID
END
0
Comment
Question by:SamCash
  • 2
  • 2
5 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 total points
ID: 40622073
Give this a whirl..
Declare @ContactID int 

-- Creating these tables for demo purposes only. 
CREATE TABLE TestContacts (ContactID int identity(1,1), Name varchar(100)) 
CREATE TABLE TestAddress (ContactID int, whatever varchar(100))

INSERT INTO TestContacts (Name) 
VALUES ('McPaddy O''Flavo') 

-- Grab the newly-created id
SET @ContactID = SCOPE_IDENTITY()

-- Now use it in another table
INSERT INTO TESTADDRESS(ContactID, whatever) 
VALUES (@ContactID, 'whatever')

SELECT * FROM TestContacts
SELECT * FROM TestAddress

Open in new window

0
 
LVL 69

Expert Comment

by:ScottPletcher
ID: 40622075
CREATE PROCEDURE [dbo].[TestAddContact]
       (
       @Name nvarchar(50)
       ,@Address nvarchar (50)
       )
AS
SET NOCOUNT ON
DECLARE @IdentityValue TABLE (
    ContactID int
    )
       
INSERT INTO dbo.TestContacts ([Name])
OUTPUT INSERTED.ContactID INTO @IdentityValue
VALUES (@Name)

INSERT INTO dbo.TestAddress ([ContactID], [Address])
SELECT ContactID, @Address
FROM @IdentityValue
0
 

Author Comment

by:SamCash
ID: 40622156
Thanks much!

Worked perfect.  I read that "SCOPE_IDENTITY()" could change if a trigger or function occurred, and "SCOPE_IDENTITY()" may not be reliable in threaded and parallel systems ... to use OUTPUT INSERTED.fieldname to be safe and allow for future if not using these now.

Thanks Again
0
 

Author Closing Comment

by:SamCash
ID: 40622158
Thanks again for the simple solution.
0
 
LVL 65

Expert Comment

by:Jim Horn
ID: 40622166
I believe you are referring to @@IDENTITY, as I haven't experienced any issues with SCOPE_IDENTITY before.  But OUTPUT is guaranteed to return the inserted.ContactID.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now