Sql 从Execute命令插入到临时表中

Sql 从Execute命令插入到临时表中,sql,sql-server,insert,execute,temporary,Sql,Sql Server,Insert,Execute,Temporary,我需要使用execute命令将select语句中的数据插入到临时表中 if OBJECT_ID('tempdb..#x') is not null drop table #x Create Table #x(aaa nvarchar(max)) declare @query2 nvarchar(max) set @query2 = 'SELECT [aaa] from IMP_TEMP' INSERT #x SELECT [aaa] from IMP_TEMP -- THIS WORKS

我需要使用execute命令将select语句中的数据插入到临时表中

if OBJECT_ID('tempdb..#x') is not null
drop table #x

Create Table #x(aaa nvarchar(max))

declare @query2 nvarchar(max)
set @query2 = 'SELECT [aaa] from IMP_TEMP'

INSERT #x
SELECT [aaa] from IMP_TEMP -- THIS WORKS
SELECT *from #x

INSERT #x
exec @query2 -- THIS DOES NOT WORKS, WHY?
SELECT *from #x

与Alex K注释不同,本地临时表在连接的所有内部作用域中都是可见的。以下代码段运行正常:

create table #tbl (id int)
exec ('select * from #tbl')
您也可以使用
insert。。。带有临时表的exec

create table #tbl (id int)
insert #tbl values (3), (1), (4)
insert #tbl exec ('select id from #tbl')

如果这不适用于您,请发布确切的错误。一个可能的罪魁祸首是插入。。。exec要求表和查询的列定义完全匹配。

您只需要在
@query2
变量周围加括号即可
EXEC
命令用于执行存储过程,
EXEC()
函数用于执行作为参数的动态sql

INSERT #x
exec (@query2)
SELECT *from #x

您是否尝试过使用正确的Syntax:

INSERT #x
exec (@query2) 
SELECT *from #x

临时表与用于执行动态sql的表不在同一范围内。/@AlexK:这些问题是关于OP希望在外部作用域中读取的内部作用域中的临时表。这个问题与此相反,这是没有问题的。Nenad Zivkovic标记为正确,因为记录了有关exec函数的更多信息
INSERT #x
exec (@query2) 
SELECT *from #x