您可以使用 Select * into 方法将数据存储在全局临时表 (##) 中,并将数据存储在 #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