SSMS / TSQL - 为查询中找到的每条记录插入多条记录

时间:2017-10-03 20:06:17

标签: sql-server tsql ssms-2016

我希望为每个匹配特定查询条件的记录插入多个记录(两个具体),其中列1的唯一ID(在两个记录中都已创建)。应该从查询的相应列中提取插入的其余值。在第一个插入中,Column2将是Column1的原始值,而第二个插入Column2将是Column2的原始值。

理想情况下,我所追求的是:

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

下面的INSERT SELECT FROM正好处理我想要做的事情,但只针对每个记录找到一个插入。

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

通过TSQL有一种简单的方法吗?我需要它批量运行,因为有数千条记录符合查询条件。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

这是一种可能性。首先使用生成第一组行的查询并将它们插入临时表。

<强> Rextester Demo

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

现在使用该临时表,我们可以使用相同的表执行UNION以生成第二组行并将它们插入到table1中。

INSERT INTO table1
SELECT 
    [uid] AS Column1
  , CAST(column1 AS NVARCHAR(3)) AS Column2
  , column3 
  , column4
  , column5
FROM #temp
UNION ALL
SELECT 
    [uid] AS Column1
  , column2
  , column3 
  , column4
  , column5
FROM #temp
ORDER BY Column1

DROP TABLE #temp