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

cas*_*One 5 sql t-sql output-clause

目前,我正在尝试update在SQL Server中执行(但它可能是任何支持该子句的DML语句),并且我想将输出放入本地临时表中,如下所示:output

update
    dbo.MyTable
set
    MyField = 30
output
    inserted.MyKeyField
into
    #myTempTable
from
    dbo.MyTable as t
where
    f.MyFilteredField = 8 
Run Code Online (Sandbox Code Playgroud)

我知道语法是正确的,根据output条款的文档(强调我的):

output_table

指定将返回的行插入的表,而不是返回给调用者.output_table可以是临时表.

这就是说,我希望它的工作就像它会在该into条款select,它只会创建表的语句.

但是,我收到以下错误:

无效的对象名称'#myTempTable'.

如何将output子句(inserteddeleted)的结果导入临时表?

cas*_*One 11

output子句不会生成新表,因此您必须事先生成与该output子句中指定的结构相匹配的表,例如:

select t.MyKeyField into #myTempTable from dbo.MyTable as t where 1 = 0
Run Code Online (Sandbox Code Playgroud)

注意,您不必使用select into上面的语法,create table也可以.最后,最简单的方法是创建一个与output子句中的字段匹配的空临时表.

创建表后,"无效对象名称"错误将消失,DML语句将无错误地执行(假设没有其他错误).

  • 不幸的是,情况确实如此,因为它意味着在失去临时表类型检测的便利性或重要的代码重复之间进行选择. (2认同)