0
 select @cols =

                STUFF((SELECT ',' + QUOTENAME(grade)         
                from #temp        
                group by grade        

        FOR XML PATH(''), TYPE        
        ).value('.', 'NVARCHAR(MAX)')         
    ,1,1,'')        

  select @colsRollup = STUFF((SELECT ', Sum(' + QUOTENAME(grade) + ') as '+QUOTENAME     (grade)        
                from #temp       
                group by grade        

        FOR XML PATH(''), TYPE        
        ).value('.', 'NVARCHAR(MAX)')         
    ,1,1,'')    

  set @query    

      =      'SELECT * into #temp3 from 
             (
              SELECT lob as "Vertical", '+ @colsRollup + '       
              FROM        
                  (        
                    SELECT lob,' + @cols + ' from         
                        (        
                         select lob,        
                           grade,        
                           asso_count        
                           from #temp        
                         ) x         
                     pivot         
                          (        
                           count(grade)        
                           for grade in (' + @cols + ')        
                           ) p         
                  ) x1 
                    GROUP BY lob with ROLLUP)x2'        

         execute(@query) 

我正在尝试创建动态列并将其插入到临时表中。但它会抛出一个错误,指出 #temp3 不是有效的对象名称。如果我不尝试将动态生成的列插入表中,则该代码有效。

4

1 回答 1

1

如果您执行代码,然后尝试访问该#temp3表,例如:

execute(@query)
select * from #temp3

我认为它会超出范围,这将解释错误消息。您可以尝试修改查询以包含SELECT类似内容:

SET @query = '
 SELECT * INTO #temp3 FROM
   (
   SELECT lob as "Vertical", '+ @colsRollup + '       
   FROM        
     (        
      SELECT lob,' + @cols + ' from (select lob, grade, asso_count from #temp) x
      PIVOT (count(grade) for grade in (' + @cols + ')) p         
      ) x1 
      GROUP BY lob with ROLLUP
     ) x2; SELECT * FROM #temp3'      

请注意最后一行现在如何包含; SELECT * FROM #temp3

如果你补充说你应该得到结果,如果那是你想要的。

于 2013-11-15T09:22:38.807 回答