When trying to build dynamic pivot tables, I keep getting the error message "Incorrect syntax near '+ @cols +'."
I've pasted the query below exactly like I am trying to run it.
Any help would be greatly appreciated.
DECLARE @cols NVARCHAR(2000)SELECT @cols = COALESCE(@cols + ',[' + COMPM_ID + ']',
'[' + COMPM_ID + ']')
FROM EDW.Excalibur.DetailSalesSuspenseComponents
ORDER BY COMPM_ID
SELECT *
FROM (
SELECT
DSS.GSL_ID,DSSC.COMPM_AMOUNT, DSSC.COMPM_ID
FROM EDW.Excalibur.DetailSalesSuspense DSS
LEFT OUTER JOIN EDW.Excalibur.DetailSalesSuspenseComponents DSSC
ON DSS.DSS_ID = DSSC.DSS_ID
WHERE DSS.PER_END_DATE >= '04/30/2012'
AND DSS.PER_END_DATE <= '04/30/2012')
AS PivotData
PIVOT (
SUM(COMPM_AMOUNT)
FOR COMPM_ID IN ( '+ @cols +' )
) AS PivotTable