0

I am inserting records from our crm to our erp. The phone table uses a identity column from the people table. I need to insert the people record and capture the value in the PersonId which is an identity column and then use that PersonId as the key to insert records to the Phone table. I get the error: Msg 137, Level 16, State 1, Line 16 Must declare the scalar variable "@IdentityID". Msg 137, Level 16, State 1, Line 17 Must declare the scalar variable "@IdentityID".

--IdentityTable
CREATE TABLE [dbo].[People](
    [People_ID] [int] NOT NULL,
    [text] [nvarchar](50) NULL,
    [PersonId] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]

--Phone
CREATE TABLE [dbo].[Phone](
    [PersonId] [int] NOT NULL,
    [text] [nvarchar](50) NULL,
    [Number] [nchar](10) NULL
) ON [PRIMARY]


declare @IdentityID table (PersonId int);

INSERT INTO [Bridge].[dbo].[People]
           ([People_ID]
           ,[text])
           output Inserted.PersonId into @IdentityID
     VALUES
           (3,'row1'),
           (4,'row2');

INSERT INTO [Bridge].[dbo].[Phone]
           (PersonId
           ,[text]
           ,[Number])
     VALUES
           (@IdentityID,'row1'),
           (@IdentityID,'row2');     

Print 'IdentityID' + @IdentityID

Msg 137, Level 16, State 1, Line 16 Must declare the scalar variable "@IdentityID". Msg 137, Level 16, State 1, Line 17 Must declare the scalar variable "@IdentityID".

1 Answer 1

1

Output will be to tablevariable you can use as below:

declare @IdentityID table (PersonId int);

INSERT INTO [dbo].[People]
           ([People_ID]
           ,[text])
           output Inserted.PersonId into @IdentityID(PersonId)
     VALUES
           (3,'row1'),
           (4,'row2');

INSERT INTO [dbo].[Phone]
           (PersonId
           ,[text]
           ,[Number])
          select PersonId,'row1', 1 from @IdentityID
          union all select PersonId,'row2', 2 from @IdentityID

select * from @IdentityID
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.