;with cte as ( SELECT * FROM ( SELECT sponsor, fundtype, amountThere is an extra not needed ( before FROM. Remove it and the query should work.
>use TipData > >declare @SQL nvarchar(max), @Columns VARCHAR(max) > >set @columns = stuff(( >select ', ' + quotename(FundType) >FROM ( >SELECT FundType >FROM LookupFundtypes P >WHERE OA=1) S >ORDER BY FundType >FOR XML PATH('')), 1,2,'') > >print @Columns > >set @SQL = >';with cte as ( >SELECT * >FROM ( >SELECT sponsor, fundtype, amount >from TIP_ApprovedFunding f >inner join TIP_Projects p on p.TipID = f.TipID >where p.ApprovedStatus = ''Active'' >) > > select * from cte > PIVOT > ( > Sum(amount) FOR [FundType] IN (' + @Columns + ') > ) > AS PivotTableAlias' > >print @SQL >execute @SQL > >>Is producing this result:
>[HSIP], [PL], [SPR], [STP], [TAP] >;with cte as ( >SELECT * >FROM ( >SELECT sponsor, fundtype, amount >from TIP_ApprovedFunding f >inner join TIP_Projects p on p.TipID = f.TipID >where p.ApprovedStatus = 'Active' >) > > select * from cte > PIVOT > ( > Sum(amount) FOR [FundType] IN ([HSIP], [PL], [SPR], [STP], [TAP]) > ) > AS PivotTableAlias > >Msg 203, Level 16, State 2, Line 34 >The name ';with cte as ( >SELECT * >FROM ( >SELECT sponsor, fundtype, amount >from TIP_ApprovedFunding f >inner join TIP_Projects p on p.TipID = f.TipID >where p.ApprovedStatus = 'Active' >) > > select * from cte > PIVOT > ( > Sum(amount) FOR [FundType] IN ([HSIP], [PL], [SPR], [STP], [TAP]) > ) > AS PivotTableAlias' is not a valid identifier. >>