如何存储已执行过程中的临时表?

时间:2019-03-20 23:32:25

标签: sql sql-server sql-manager

我有以下代码:

SELECT @Name = [TrigTable] 
FROM [dbo].[setdevelopmentjob] 
WHERE [TrigTable] IS NOT NULL

PRINT @Name

SET @sql = 'SELECT * FROM ' + @Name;

#TriggerTable = EXEC sp_executesql @sql;

SELECT * FROM #TriggerTable

很显然,行#TriggerTable = Exec sp_executesql @sql的语法不正确,但是它显示了我要执行的操作。这些列是变量,这意味着我不能只声明一个表变量。如何将执行过程的输出传递给#TriggerTable

1 个答案:

答案 0 :(得分:3)

您可以使用Select *将数据存储在全局临时表(##)中,并存储在#temp表中,您必须首先创建该表,我在使用动态sql时就知道该表,但是您当然可以做到这一点在运行时,但仍然可能需要一些物理表才能访问它。

create table testtmp (id int, namen varchar(15)) 

--inserting the data into physical table 
insert into testtmp (id, namen)

select 1 as ID, 'XYZ' as namen union all
select 2 as ID, 'ABC' as namen union all
select 3 as ID, 'DIG' as namen

create table #temp (ID int) 

declare @sql nvarchar(max) = 'select ID from testtmp' 
insert into #temp exec sp_executesql @sql 

select * from #temp 

Gives you this output: 

 ID 
  1 
  2 
  3 

使用全局临时表,您可以轻松地做到这一点,而不必创建任何表,可以根据需要指定列名。

 declare @sql nvarchar(max) = 'select * into ##Gloabltmptest from testtmp' 
 exec sp_executesql @sql 

 select * from ##Gloabltmptest 

输出:

 ID  namen
 1  XYZ
 2  ABC
 3  DIG

还添加了表变量,类似于#temp表。

declare @table table (IDtab int, nametab varchar(15)) 

declare @sql nvarchar(max) = 'select * from testtmp' 
insert into @table exec sp_executesql @sql 

select * from @table