EXECUTE(@QUERY)
所以如何将EXECUTE(@QUERY)的动态输出保存到临时表中。
答案 0 :(得分:1)
您可以使用global temp table
select create
和sql 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