日期:2014-05-17  浏览次数:20509 次

MS-SQL取连续日期问题
表A


我现在需要得出表A中所有FBeginDate和FEndDate字段间的日期

------解决方案--------------------
你看看,是这样吗


--drop table tb

create table tb(FBeginDate datetime,FEndDate datetime)

insert into tb
select '2010-10-01','2010-10-01'
union all select '2010-10-01','2010-10-07'
union all select '2011-01-30','2011-02-12'


;with t
as
(
select 1 as number
union all
select number + 1
from t
where t.number < 100
)

select tb.FBeginDate,
       tb.FEndDate,
       dateadd(day,t.number-1,FBeginDate) as '两个日期之间的天'
from tb
inner join t
        on datediff(day,FBeginDate,FEndDate) +1 >= t.number
order by tb.FBeginDate,
         '两个日期之间的天'
         
/*
FBeginDate             FEndDate             两个日期之间的天
2010-10-01 00:00:00.000 2010-10-01 00:00:00.000 2010-10-01 00:00:00.000
2010-10-01 00:00:00.000 2010-10-07 00:00:00.000 2010-10-01 00:00:00.000
2010-10-01 00:00:00.000 2010-10-07 00:00:00.000 2010-10-02 00:00:00.000
2010-10-01 00:00:00.000 2010-10-07 00:00:00.000 2010-10-03 00:00:00.000
2010-10-01 00:00:00.000 2010-10-07 00:00:00.000 2010-10-04 00:00:00.000
2010-10-01 00:00:00.000 2010-10-07 00:00:00.000 2010-10-05 00:00:00.000
2010-10-01 00:00:00.000 2010-10-07 00:00:00.000 2010-10-06 00:00:00.000
2010-10-01 00:00:00.000 2010-10-07 00:00:00.000 2010-10-07 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-01-30 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-01-31 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-01 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-02 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-03 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-04 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-05 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-06 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-07 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-08 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-09 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-10 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-11 00:00:00.000
2011-01-30 00:00:00.000 2011-02-12 00:00:00.000 2011-02-12 0