Search code examples
sql-servert-sqlssms-16

SSMS / TSQL - Insert multiple records for every record found in query


I want to insert multiple records (two to be specific) with a unique ID for Column 1 (in both records created) for every record that matches a specific query criteria . The rest of the values for the insert should be pulled from the respective columns on the query. In the first insert Column2 will be the original value from Column1, and on the second insert Column2 will be the original value from Column2.

Ideally, what I'm after is:

FIND RECORDS THAT MEETS CRITERIA
FOR EACH RECORD
GENERATE GUID
INSERT TWO NEW RECORDS WITH GUID AS COLUMN1, AND REMAINING COULMNS FROM 
CURRENT RECORD FOUND

RECORDS
123 abc 3 4 5
456 def 6 7 8

RECORD 1
123 abc 3 4 5

NEW RECORDS AFTER INSERTS
UID1 123 3 4 5
UID1 abc 3 4 5

ROW 2
456 def 6 7 8

NEW RECORDS AFTER INSERTS
UID2 456 6 7 8
UID2 def 6 7 8

The below INSERT SELECT FROM handles exactly what I want to do but only for a single insert per record found.

INSERT INTO table1
( 
    Column1,
    Column2,
    Column3
    Column4
    Column5
)
SELECT
    NEWID(), -- unique ID
    Column2, -- or Column1 based on which insert we are doing
    Column3, -- always column 3
    Column4, --always column 4
    Column5 -- always column 5
FROM
    table1
WHERE Column1 IS NOT NULL
AND Column1 != Column4

Is there an easy way to do this via TSQL? I need it to run in bulk, for a potential of thousands of records meeting the query conditions.


Solution

  • WITH xQ(UUID,Column2,Column3,Column4,Column5) AS 
    ( 
        SELECT
            NEWID(),
            Column1,
            Column2,
            Column3,
            Column4,
            Column5 
        FROM
            table1
        WHERE Column1 IS NOT NULL
        AND Column1 != Column4
    )
    
    INSERT INTO table1
    ( 
        Column1,
        Column2,
        Column3,
        Column4,
        Column5
    )
    SELECT
        UUId, 
        Column1,
        Column3,
        Column4,
        Column5 
    FROM xQ
    UNION
    SELECT
        UUId,
        Column2,
        Column3,
        Column4,
        Column5 
    FROM xQ