views:

36

answers:

1

I'm trying to write a SQL script that inserts 2 rows into a table thus:

INSERT INTO [table1]
       ([Id]
       ,[Name]
       ,[SequenceNo]
       ,[EntityId])
 VALUES
       (<newid(), uniqueidentifier,>
       ,<'SpecificName1', nvarchar(255),>
       ,<1, int,>
       ,</*Here's where I need help*/>)
INSERT INTO [table1]
       ([Id]
       ,[Name]
       ,[SequenceNo]
       ,[EntityId])
 VALUES
       (<newid(), uniqueidentifier,>
       ,<'SpecificName2', nvarchar(255),>
       ,<2, int,>
       ,</*Here's where I need help*/>)

"EntityId" is a foreign key to a table I call "Entities" here.

Is there a way I can insert 2 of these rows for each row I have in "Entities" (with the respective Entity's Id column value as the value for table1's EntityId column without using a cursor ?

+1  A: 

An INSERT SELECT should be what you need. I'm not sure if you might need a WHERE clause to only insert any relevent entities though...

EDIT: My first answer didn't increment the sequence no for each item in Entity. Have used the ROW_NUMBER method to do this.

INSERT INTO [table1]
(
    [Id],
    [Name],
    [SequenceNo],
    [EntityId]
)
SELECT
    NEWID(),
    'SpecificName1',
    ROW_NUMBER() OVER (ORDER BY EntityId),
    EntityId
FROM
    Entities
Robin Day