2013-11-15 76 views
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不是有效的對象名稱。如果我不嘗試將動態生成的列插入到表中,代碼將起作用。SQL動態列

+1

mysql或sql-server?選擇一個並編輯標籤。 (它看起來像SQL服務器) – slavoo

+0

嗨,其SQL Server。 –

+0

@prasanthunnikrishnan你怎麼執行這個?在存儲過程或其他方式? – jpw

回答

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

如果你補充一點,你應該得到的返回結果,如果這是你想要的。

+1

謝謝。它正在工作。 :) –