选择sql数据透视表

时间:2016-02-22 16:03:23

标签: sql-server pivot

我正在尝试将以字符串形式完成的pivoted表插入到临时表#temp中。原始代码如下。

declare @list as varchar(max)
declare @sql varchar(max)
SELECT @list = COALESCE(@list + ',[' + cast(rank as varchar) + ']', '[' + cast(rank as varchar)+ ']')
from (
  select distinct rank
  from #pp
  where INSTR_ROLE = 'PI'
) x

set @sql ='select distinct * from (SELECT DISTINCT A.EMPLID AS EMPLID, 
                ''Yes'' AS prime, 
                (A.SUBJECT + '' '' +  A.CATALOG_NBR) AS Class, 
                rank
      FROM #pp A
      WHERE (A.INSTR_ROLE = ''PI'')
) as s
pivot ( max(class)
    for rank in ('+@list+')
) as pvt'

exec(@sql)

我创建表的方法是指定select into #temp,但是当我执行时,它表示找不到#temp表。有没有办法实现这个目标?

set @sql ='select distinct * into #temp from (SELECT DISTINCT A.EMPLID AS EMPLID, 
                ''Yes'' AS prime, 
                (A.SUBJECT + '' '' +  A.CATALOG_NBR) AS Class, 
                rank
      FROM #pp A
      WHERE (A.INSTR_ROLE = ''PI'')
) as s
pivot ( max(class)
    for rank in ('+@list+')
) as pvt'

1 个答案:

答案 0 :(得分:2)

在动态查询之外无法访问动态查询中创建的临时表。

动态查询将具有与执行动态查询的当前会话不同的会话。因此,当您尝试选择动态查询的临时表外,其中临时表在动态查询中创建,它将抛出错误,表示temp不存在。

但是当你尝试在动态查询中选择临时表时,它将起作用。

set @sql ='select distinct * into #temp from (SELECT DISTINCT A.EMPLID AS EMPLID, 
                ''Yes'' AS prime, 
                (A.SUBJECT + '' '' +  A.CATALOG_NBR) AS Class, 
                rank
      FROM #pp A
      WHERE (A.INSTR_ROLE = ''PI'')
) as s
pivot ( max(class)
    for rank in ('+@list+')
) as pvt;

select * from #temp' 

如果查询不会在不同的会话中并行执行,则可以使用global temp table而不是临时表。

全局临时表可以在动态查询之外访问,即使它是在动态查询中创建的。

 set @sql ='select distinct * into ##temp from (SELECT DISTINCT A.EMPLID AS EMPLID, 
                ''Yes'' AS prime, 
                (A.SUBJECT + '' '' +  A.CATALOG_NBR) AS Class, 
                rank
      FROM #pp A
      WHERE (A.INSTR_ROLE = ''PI'')
) as s
pivot ( max(class)
    for rank in ('+@list+')
) as pvt'

select * from ##temp