Home Forums Programming General Linked Primary Keys after INSERT within the same table RE: Linked Primary Keys after INSERT within the same table

  • do you mean how do you get teh newly created PK values for data you inserted? especially so you can then do a subsequent insert into a child table?

    the answer there , i think, is that you want to look at the OUTPUT clause;

    here's a simple example, but the details and columns would be specific yto your tables.

    CREATE TABLE adds(

    adid INT IDENTITY(1,1) NOT NULL PRIMARY KEY,

    code VARCHAR(30) )

    DECLARE @MyResults TABLE(

    ID int,

    newcode VARCHAR(30),

    oldcode VARCHAR(30) )

    Create Table adds(adid int identity(1,1) not null primary key, code varchar(30) )

    INSERT INTO adds(code)

    OUTPUT

    INSERTED.adid,

    INSERTED.code,

    NULL

    INTO @MyResults

    SELECT 'aliceblue' UNION ALL SELECT 'antiquewhite' UNION ALL

    SELECT 'aqua*' UNION ALL SELECT 'aqua*' UNION ALL

    SELECT 'aquamarine' UNION ALL SELECT 'azure' UNION ALL

    SELECT 'beige' UNION ALL SELECT 'bisque' UNION ALL

    SELECT 'black*' UNION ALL SELECT 'black*' UNION ALL

    SELECT 'blanchedalmond' UNION ALL SELECT 'blue*' UNION ALL

    SELECT 'blue*' UNION ALL SELECT 'blueviolet' UNION ALL

    SELECT 'brown' UNION ALL SELECT 'burlywood' UNION ALL

    SELECT 'cadetblue'

    declare @MyResults TABLE(ID int,newcode varchar(30),oldcode varchar(30) )

    --now that i have the new keys in a table variable, i can isnert into another, related, child table, or update something based on these new ID's

    UPDATE dbo.adds

    SET code = UPPER(SUBSTRING(code, 1, LEN(code) - 3) )

    OUTPUT

    INSERTED.adid,

    INSERTED.code,

    DELETED.code

    INTO @MyResults

    WHERE LEFT(code,1) = 'a'

    SELECT * FROM @MyResults

    --results of update

    ID newcode oldcode

    1 ALICEB aliceblue

    2 ANTIQUEWH antiquewhite

    3 AQ aqua*

    4 AQ aqua*

    5 AQUAMAR aquamarine

    6 AZ azure

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!