>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 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 >>
>[HSIP], [PL], [SPR], [STP], [TAP] >;with cte as ( >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 31 >The name ';with cte as ( >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. >Did you try running
;with cte as ( 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 PivotTableAliasThis should work.