DECLARE @s nvarchar(4000), @dt datetime
SET @dt = '2006-02-12'
SET @s = ''
WHILE @dt < = GETDATE()
SELECT @s = @s + ',' 
+ QUOTENAME(STUFF(CONVERT(char(5), @dt, 101), 3, 1, '月')+'日')
+ ' = MAX(CASE WHEN ''' + CONVERT(CHAR(10), @dt, 112) + '''
BETWEEN hiFirstDate AND ISNULL(hiEndDate, GETDATE()) THEN hiName END)',
@dt = @dt + 1
EXEC('SELECT hrRoomName ' + @s + ' FROM V_Room_In GROUP BY hrRoomName')

解决方案 »

  1.   

    create table V_Room_In
    (
       hrRoomName varchar(3),
       hiName varchar(5),
       hiFirstDate datetime,
       hiEndDate datetime
    )
    insert V_Room_In select '101','甲','2006-2-13','2006-2-14'
    insert V_Room_In select '101','乙','2006-2-17','2006-2-18'
    insert V_Room_In select '102','丙','2006-2-13','2006-2-14'
    insert V_Room_In select '103','丁','2006-2-13',NUll
    insert V_Room_In select '103','戊','2006-2-17',NUll
    --视图
    create view VV_Room_In
    as
    select hrRoomName,hiName,hiFirstDate,isnull(hiEndDate,getdate()) as hiEndDate from V_Room_In
    --函数
    create function T_txt(@id varchar(3),@T_date datetime)
    returns varchar(8000)
    as
    begin
       declare @T_SQL varchar(8000)
       set @T_SQL=''
       select @T_SQL=@T_SQL + hiName +',' from VV_Room_In where hrRoomName=@id and @T_date between  hiFirstDate and hiEndDate
       if len(@T_SQL)>0 
         set @T_SQL=left(@T_SQL,len(@T_SQL)-1)
       return @T_SQL
    end
    create proc T_proc
    as
    declare @T_SQL varchar(8000)
    declare @begin datetime
    declare @end datetime
    declare @i int
    declare @j int
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#T]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[#T]
    create table #T (T_date datetime)
    select @begin=min(hiFirstDate) from V_Room_In
    set @end=getdate()
    set @j=datediff(dd,@begin,@end)
    set @i=0
    set @T_SQL=''
    while @i<=@j
    begin
      insert #T select dateadd(dd,@i,@begin)
      set @i=@i+1
    end
    select @T_SQL=@T_SQL +'max(case when T.T_date=''' + convert(char(10),T_date,120)  + ''' then dbo.T_txt(V.hrRoomName,T.T_date) else '''' end) as  ''' + convert(char(10),T_date,120) +''', ' from  #T
    set @T_SQL='select V.hrRoomName,' +left(@T_SQL,len(@T_SQL)-1) + ' from #T T,(select distinct hrRoomName from V_Room_In) V group by V.hrRoomName'
    exec (@T_SQL)exec T_proc