Here's a set based alternative--sample table for illustrationcreate table tst(UserName varchar(2),[Description] varchar(10),StartDate datetime,EndDate datetime)insert tstvalues('A','AAA','01/Oct/2010 8:00:00','03/Oct/2010 18:00:00'),('B','BBB','01/Oct/2010 13:00:00','01/Oct/2010 18:00:00'),('C','CCC','03/Oct/2010 13:00:00','03/Oct/2010 13:00:00'),('D','DDD','01/Oct/2010 08:00','02/Oct/2010 12:00:00'),('E','EEE','02/Oct/2010 08:00:00','02/Oct/2010 12:00:00')select p.UserName,DATEADD(dd,DATEDIFF(dd,-number,StartDate),0) AS DateVal ,DATEADD(dd,DATEDIFF(dd,-number,StartDate),Start) AS STart,DATEADD(dd,DATEDIFF(dd,-number,StartDate),[End]) AS [ENd],SlotINTO tempfrom tst pcross join master..spt_values vcross join (SELECT 'AM' AS Slot,'08:00' AS STart,'12:00' AS [ENd] UNION ALL SELECT 'PM' AS Slot,'13:00' AS STart,'18:00' AS [ENd] )t WHERE v.number BETWEEN 0 AND DATEDIFF(dd,startdate,enddate) and v.type='p'DECLARE @DateList varchar(5000)=''DECLARE @SQL varchar(max)SET @DateList= STUFF((SELECT DISTINCT ',['+ CONVERT(varchar(11),DateVal,121) + Slot + ']'FROM tempORDER BY ',['+ CONVERT(varchar(11),DateVal,121) + Slot + ']' FOR XML PATH('')),1,1,'') --SELECT @DateList SET @SQl='SELECT UserName,COALESCE(' + REPLACE(@DateList,',',',''---''),COALESCE(') + ',''---'') FROM ( SELECT m.UserName,CONVERT(varchar(11),DateVal,121) + Slot AS DateSlot,COALESCE(n.[Description],''---'') AS DescriptionFROM temp m LEFT JOIN tst n ON n.UserName=m.UserName AND (m.STart BETWEEN n.StartDate AND n.EndDate OR m.[ENd] BETWEEN n.StartDate AND n.EndDate) )t PIVOT (MAX(Description) FOR DateSlot IN (' + @DateList + '))p' EXEC(@SQL)--destroy tables after useDROP TABLE tempDROP TABLE tstoutput----------------------------------------------------------------------------------------------------------------UserName 2010-10-01 AM 2010-10-01 PM 2010-10-02 AM 2010-10-02 PM 2010-10-03 AM 2010-10-03 PM-----------------------------------------------------------------------------------------------------------------A AAA AAA AAA AAA AAA AAAB --- BBB --- --- --- ---C --- --- --- --- --- CCCD DDD DDD DDD --- --- ---E --- --- EEE --- --- ---
------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs