0

Can someone explain me the meaning of the ' symbol in the second block? I found this old post dealing with pivot and the set @query is put into these symbols' while the first one is not (the select @cols). What is the meaning of that? Why it needs to be done like that?

Convert Rows to columns using 'Pivot' in SQL Server

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Week) 
                    from yt
                    group by Week
                    order by Week
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT store,' + @cols + ' from 
             (
                select store, week, xCount
                from yt
            ) x
            pivot 
            (
                sum(xCount)
                for week in (' + @cols + ')
            ) p '

execute(@query);
Community
  • 1
  • 1
  • "Why it needs to be done like that?" when dealing with a dynamic number of columns in a pivot, dynamic SQL must be used. The @Cols simply is the list of columns the user wants to pivot. – xQbert Jul 25 '16 at 19:46

1 Answers1

1

The second block is using dynamic query evaluation. The ' symbols are simply string literal delimiters.

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40