• The problem is a subquery is being used but not aliased. It is when the variable @query is being defined

    To fix it change to:

    set @query = '

    DECLARE @cols NVARCHAR(max)

    SELECT @cols = STUFF(

    ( SELECT DISTINCT ' + case when @colTop is not null then 'Top ' + @colTop else '' end + '''],['' + t2.' + @pivotField + '

    FROM

    (SELECT CONVERT(nvarchar(max),a.' + @colField + ') AS ' + @pivotField + '

    FROM

    (SELECT DISTINCT ' + @colField + '

    FROM ' + @colTable + ' x

    ' + case when @colWhere is not null then 'WHERE ' + @colWhere else '' end + '

    ) AS a

    ) AS t2

    ORDER BY ''],['' + t2.' + @pivotField + ' FOR XML PATH('''')

    ), 1, 2, '''') + '']''

    select @cols

    '

    All I have added is ' x '

    Hope this helps

    Phil