Get all dates in date range in SQL Server

前端 未结 3 1816
清酒与你
清酒与你 2020-12-03 13:16

I got this example from one StackOverflow question that was asked but I couldn\'t get it work according to my need.

WITH DateTable
AS
(
    SELECT CAST(\'201         


        
3条回答
  •  北海茫月
    2020-12-03 13:42

    With a little help of a numbers table.

    declare @T table
    (
      ID int identity primary key,
      FromDate date,
      ToDate date
    )
    
    insert into @T values
    ('2011-11-10', '2011-11-12'),
    ('2011-12-12', '2011-12-14')
    
    select row_number() over(order by D.Dates) as SN,
           D.Dates
    from @T as T
      inner join master..spt_values as N
        on N.number between 0 and datediff(day, T.FromDate, T.ToDate)
        cross apply (select dateadd(day, N.number, T.FromDate)) as D(Dates)
    where N.type ='P'
    

    Try on SE Data

提交回复
热议问题