如何在SELECT / INTO语句中使用OUTPUT子句

时间:2018-02-22 16:11:32

标签: sql sql-server tsql sql-server-2012

我有以下查询

SELECT 'Luke' AS [Jedi_names], 'Skywalker' AS [Jedi_surname]
INTO #Jedi

CREATE临时表#JediINSERT里面的数据。

我想使用OUTPUT来显示我在表中保存的数据,但我无法理解如何使用OUTPUT子句而不会收到错误消息

  

“输出'附近的语法不正确。”

INSERT INTO查询中,我会写下以下内容

INSERT INTO #Jedi([Jedi_names],[Jedi_surname])
OUTPUT INSERTED.*
SELECT 'Luke' AS [Jedi_names], 'Skywalker' AS [Jedi_surname]

但如果表已经创建,那么这只是INSERT行。

是否可以在第一个查询中使用OUTPUT子句?

4 个答案:

答案 0 :(得分:2)

请使用如下

CREATE TABLE #Jedi([Jedi_names] VARCHAR(20),[Jedi_surname] VARCHAR(20))

INSERT INTO #Jedi([Jedi_names],[Jedi_surname])
OUTPUT INSERTED.*
SELECT * FROM 
(
    SELECT 'Luke' AS [Jedi_names], 'Skywalker' AS [Jedi_surname]
)K

<强>输出

Jedi_names  Jedi_surname
Luke    Skywalker

答案 1 :(得分:2)

您无法在output语句中使用select子句。它仅适用于insertupdatedeletemerge

另一种选择是分两部分: 首先,创建没有记录的临时表:

SELECT 'Luke' AS [Jedi_names], 'Skywalker' AS [Jedi_surname]
INTO #Jedi 
WHERE 1=0

然后,使用insert...output...select

将记录插入临时表
INSERT INTO #Jedi
OUTPUT INSERTED.*
SELECT 'Luke' AS [Jedi_names], 'Skywalker' AS [Jedi_surname]

答案 2 :(得分:1)

这是您之后的语法:

CREATE TABLE #Jedi ([Jedi_forename] varchar(50),
                    [Jedi_surname] varchar(50));

INSERT INTO #Jedi ([Jedi_forename],[Jedi_surname])
OUTPUT Inserted.*
SELECT 'Luke' AS [Jedi_names], 'Skywalker' AS [Jedi_surname]

DROP TABLE #Jedi;

您无法在同一声明中使用OUTPUTINTO

答案 3 :(得分:-1)

select into将避免记录。使用insert into的那一刻,它就无法实现目的。