动态变量存储导致临时表和变量错误

时间:2014-05-01 15:59:08

标签: sql

我有一个部分有效的动态PIVOT。当我不使用变量请求where子句但只使用特定数字时,它可以工作。

我还希望能够将结果存储到临时表中。

是否可以在动态数据透视中使用where子句变量,是否可以将结果保存到临时表?

这是我当前无效的查询

declare @CourseID int = 2
DECLARE  
  @cols AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(UnitID) 
            FROM LMS_Unit_Status where CourseID = @CourseID
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT LearnerID, ' + @cols + ' from 
             (select LearnerID,UnitID,Completed from LMS_Unit_Status where CourseID = @CourseID) as s
            pivot 
            (
                min(Completed)
                for UnitID in (' + @cols + ')
            ) p' 
 execute(@query);

Msg 137, Level 15, State 2, Line 2
Must declare the scalar variable "@CourseID".

由于

1 个答案:

答案 0 :(得分:0)

如果@CurseID是变量解析器应该知道它是变量而不是字符串

由于您不知道有多少列表,您只需使用select into语句。

set @query = 'SELECT LearnerID, ' + @cols + ' into tempTable from
             (select LearnerID,UnitID,Completed from LMS_Unit_Status where CourseID = ' + @CourseID + ') as s
            pivot 
            (
                min(Completed)
                for UnitID in (' + @cols + ')
            ) p
 select * from tempTable
 drop table tempTable' 
 execute(@query);

干杯!