• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 142
  • Last Modified:

One sproc to insert multiple linked tables, and conditionly modify a field of the just inserted record with the inserted records ID

I am using the following sql sproc to get the Identity of an INSERT to use in subsequent INSERTs of linked tables (thanks Experts Exchange).

(@field1, @field2, @field3, @field4)

 DECLARE @IdentityValue as TABLE(ContactID int);

INSERT INTO primarytable field1, field2
OUTPUT INSERTED.ContactID INTO @IdentityValue -- To get the ID of the inserted record
VALUES @field1, @field2

INSERT INTO linktable field3, field4
SELECT ContactID, @field3, @field4
FROM @IdentityValue

I do not fully understand how this works, but it INSERTs the right data in my tables.

Now in the same sproc I need to INSERT(UPDATE) the @IdentityValue ContactID INTO linktable field4
non working example to illustrate what I am attempting to do:

IF (@flag != 0)

    UPDATE linktable
    SET field4 = @IdentityValue.ContactID  -- yes the ID field and the field4 will be the same
    WHERE linktable.fieldID = @IdentityValue.ContactID --the record just inserted above


Thanks Much
1 Solution
ste5anSenior DeveloperCommented:
Yup, @IdentityValue is a table, thus you need a different UPDATE syntax:

SET     field4 = IV.ContactID
FROM    linktable LT
        INNER JOIN @IdentityValue IV ON LT.fieldID = IV.ContactID;above

Open in new window

SamCashAuthor Commented:

Thanks much!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now