TSQL INSERT INTO SELECT - 显示行

时间:2014-05-28 07:11:25

标签: sql tsql select insert

是否可以通过此查询显示我插入的行:

INSERT INTO dbo.Table (Col1, Col2, Col2)
    (SELECT
        Col1,
        Col2,
       'Something modified',
    FROM dbo.Table
    WHERE Col10 = 66)

使用它的PrimaryKey值等获取整个新行非常重要,不仅仅是Col1,Col2,Col3

1 个答案:

答案 0 :(得分:7)

OUTPUT条款现在是您的朋友:

INSERT INTO steam.DocumentGeographies (Col1, Col2, Col3)
OUTPUT inserted.*
    (SELECT
        Col1,
        Col2,
       'Something modified',
    FROM dbo.Table
    WHERE Col10 = 66)

您可以通过使用OUTPUT子句指定目标表或将查询包装为子查询来插入INTO的结果:

INTO条款

当您想将相同的数据插入两个表时,这很有用。您始终可以在OUTPUT子句中列出所需的文件(inserted.Col1,inserted.Col2)

INSERT INTO steam.DocumentGeographies (Col1, Col2, Col3)
    OUTPUT inserted.* INTO DestinationTableName(Col1, Col2, Col3)
        (SELECT
            Col1,
            Col2,
           'Something modified',
        FROM dbo.Table
        WHERE Col10 = 66)

<强> SUBQUERY

当您想要将OUTPUT连接到另一个表或想要进行计算(如求和或计数值)并将这些结果插入另一个表时,这很有用。

INSERT INTO DestinationTableName
(Col1, Col2, Col3)
SELECT Col1, Col2, Col3 FROM (
    INSERT INTO steam.DocumentGeographies (Col1, Col2, Col3)
    OUTPUT inserted.*
        (SELECT
            Col1,
            Col2,
           'Something modified',
        FROM dbo.Table
        WHERE Col10 = 66)
) TMP