Link to home
Start Free TrialLog in
Avatar of SamCash
SamCashFlag for United States of America

asked on

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

--
-- 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
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of SamCash

ASKER

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
Avatar of SamCash

ASKER

Thanks again for the simple solution.
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.