﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / SQL Server 2008 / T-SQL (SS2K8)  / PIVOT Operator with Dynamic Columns / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Tue, 21 May 2013 13:59:36 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: PIVOT Operator with Dynamic Columns</title><link>http://www.sqlservercentral.com/Forums/Topic1423275-392-1.aspx</link><description>You might want to look into the Dynamic Cross Tab approach as referenced in my signature.Might be the less strugglig way to achieve what you're looking for.As a side note: I'd recommend you get used to use sp_executesql instead of Exec() due to security issues (SQL injection). It might not be an issue in this case, but in another one you might need to deal with...</description><pubDate>Sat, 23 Feb 2013 03:05:49 GMT</pubDate><dc:creator>LutzM</dc:creator></item><item><title>PIVOT Operator with Dynamic Columns</title><link>http://www.sqlservercentral.com/Forums/Topic1423275-392-1.aspx</link><description>The following syntax works except I would like to add a text string(Time) to the beginning of the field names created by the pivot operator. I have added a commented out line of code starting at COALESCE which has the syntax I attempted to use to add the string to the beginning of the field name. It adds the text string to the field name but the syntax fails to add values into these fields, they are all null. Any suggestions?DECLARE @columns VARCHAR(8000)--declare variable to store all the date values in column DateSELECT @columns = --COALESCE(@columns + ',[' + 'Time' +  cast(DATEPART(week, Date) as varchar) + ']','[' + 'Time' +  cast(DATEPART(week, Date) as varchar)+ ']')COALESCE(@columns + ',[' + cast(left(Date, 11) as varchar) + ']','[' + cast(left(Date, 11) as varchar)+ ']')FROM Avg_Utilization group by left(Date, 11) order by LEFT(DATE, 11)select @columnsdeclare @query varchar(8000)SET @query ='select * into avgpivotjunk from (select node, left(date, 11) as Date, avg_utilization from Avg_Utilization)apivot(sum(Avg_Utilization) for date in('+ @columns +'))as p'execute (@query)</description><pubDate>Fri, 22 Feb 2013 15:09:26 GMT</pubDate><dc:creator>scott.k.ballard</dc:creator></item></channel></rss>