创建临时表并同时存储执行命令的结果



我有一个存储过程,我在其中运行/执行一个声明的变量,该变量被设置为透视表的选择查询,重要的是该透视表正在将列转换为n行。是的,行不是固定的,这就是为什么我在创建一个具有固定列的临时表时遇到问题。我想要的是通过执行execute命令来创建一个临时表,这样列将由select/insert语句确定。以下是查询。

SELECT @cols = @cols + QUOTENAME(item) + ',' 
FROM (select distinct item from #TableData ) as tmp
select @cols = substring(@cols, 0, len(@cols)) 

set @tequery = 
'SELECT * from 
(
select Sno, item, SoldValue from #TableData
) mytbl
pivot 
(
max(ValueInDhs) for GroupName in (' + @cols + ')
) newTable'
execute(@tablequery)

我想把@tequery的结果存储到一个临时表中,或者更好的是,这个存储过程应该返回结果集,而不是int,因为这个过程我已经插入到我的实体框架中,它显示(插入后)它的返回类型为int。

您可以使用全局(##)临时表来执行此操作,尽管您必须小心多个进程同时执行此操作。这里有一个简单的例子:

declare @sql varchar(max) = '
select *
into ##temp -- create global temp table
from   (
select name
, create_date = convert(varchar(4), create_date, 102) 
from   sys.objects) as o
pivot ( count(name) for create_date in ([2017],[2016],[2012], [2009],[2003])
) as p;
'
exec (@sql)
-- if you do not want to use the global table, select it into a temp table
select * into #temp from ##temp
-- and drop the global
drop table ##temp
select * from #temp

最新更新