简体   繁体   English

如何在SQL中使用output子句输出插入,更新,删除结果到新的临时表?

[英]How to use output clause in SQL to output insert, update, delete results into new temporary table?

Currently, I'm trying to perform an update in SQL Server (but it could be any DML statement that supports the output clause ), and I'd like to put the output into a local temp table, like so: 目前,我正在尝试在SQL Server中执行update (但它可能是任何支持output子句的 DML语句 ),并且我想将输出放入本地临时表中,如下所示:

update
    dbo.MyTable
set
    MyField = 30
output
    inserted.MyKeyField
into
    #myTempTable
from
    dbo.MyTable as t
where
    f.MyFilteredField = 8 

I know the syntax is correct, as per the documentation for the output clause (emphasis mine): 我知道语法是正确的,根据output子句的文档(强调我的):

output_table output_table

Specifies a table that the returned rows are inserted into instead of being returned to the caller. 指定将返回的行插入的表,而不是返回给调用者。 output_table may be a temporary table . output_table可以是临时表

That said, I'd expect it to work just like it would on the the into clause on a select statement in that it would just create the table. 也就是说,我希望它能像在select语句中的into子句中一样工作,因为它只会创建表。

However, I get the following error: 但是,我收到以下错误:

Invalid object name '#myTempTable'. 无效的对象名称'#myTempTable'。

How can I get the results of the output clause ( inserted or deleted ) into a temp table? 如何将output子句( inserteddeleted )的结果输入临时表?

The output clause will not generate a new table, so you have to generate the table beforehand which matches the structure of what is specified in the output clause , for example: output子句不会生成新表,因此您必须事先生成表, 该表与output子句中指定的结构相匹配 ,例如:

select t.MyKeyField into #myTempTable from dbo.MyTable as t where 1 = 0

Note, you don't have to use the select into syntax above, create table works just as well. 注意,您不必使用上面的select into语法, create table也可以。 In the end, whatever is easiest to create an empty temporary table that matches the fields in your output clause. 最后,最简单的方法是创建一个与output子句中的字段匹配的空临时表。

Once the table is created, the "Invalid object name" error will go away and the DML statement will execute without error (assuming there are no other errors). 创建表后,“无效对象名称”错误将消失,DML语句将无错误地执行(假设没有其他错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM