如何在EXECUTE(@QUERY)中的Temp Table中存储数据,其中EXECUTE(@QUERY)返回动态表

时间:2016-03-15 10:57:45

标签: sql-server sql-server-2008

EXECUTE(@QUERY)
  1. 返回动态列
  2. 如果我想在临时表中存储数据,那么我必须首先使用列和数据类型声明临时表。但我不知道EXECUTE(@QUERY)返回了多少列。
  3. 所以如何将EXECUTE(@QUERY)的动态输出保存到临时表中。

2 个答案:

答案 0 :(得分:1)

您可以使用global temp table

中的select createsql server语句执行此操作
declare @QUERY nvarchar(500)
set @QUERY = 'select c1, c2, c3 from test_table'

declare @create_sql nvarchar(500)
set @create_sql = 'select * into ##temp_tbl from ('+ @QUERY + ') as x'
EXEC sp_executesql @create_sql

select * from ##temp_tbl

此处select * into ##temp_tbl将创建##temp table

答案 1 :(得分:1)

这是OpenRowSet的解决方案。您只需将所有使用临时表的工作放在动态sql中(或者您可以使用全局临时表)

declare @Query nvarchar(max)
set @Query = 
'
select 1 as FirstColumn, ''Hello'' as SecondColumn, GetDate() as ThirdColumn
union
select 2 as FirstColumn, ''world'' as SecondColumn, GetDate() as ThirdColumn
'

execute(@Query)

declare @sql nvarchar(max)
set @sql = 

'
select * into #MyTempTable 
from OPENROWSET(''SQLNCLI'', ''Server=(local);Trusted_Connection=yes;'', '''+ Replace(@Query, '''', '''''') +''')

select * from #MyTempTable
'

exec sp_executeSQL @sql

-- global table example
set @sql = 

'
select * into ##MyTempTableGlobal 
from OPENROWSET(''SQLNCLI'', ''Server=(local);Trusted_Connection=yes;'', '''+ Replace(@Query, '''', '''''') +''')
'

exec sp_executeSQL @sql

select * from ##MyTempTableGlobal
相关问题