简体   繁体   中英

Dynamic variable store results in temp table and variable error

I have a dynamic PIVOT that partially works. It works when I don't request a where clause using a variable but just use a specific number.

I also want to be able to store the results into a temp table.

Is it possible to have a where clause variable in a dynamic pivot and is it possible to save the results to a temp table?

Here is my current query that is not working

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".

Thanks

If @CurseID is a variable parser should know it is a variable and not a string

And since you have no idea how many columns table will have you can simply use select into statement.

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);

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM