如何在SQL Server中给出一天的日期范围之间获取日期

时间:2017-02-10 15:36:01

标签: sql sql-server tsql sql-server-2012

假设:

  • DateFrom:01-01-2017
  • DateTo:02-10-2017
  • 日:星期一

我需要获得此输出:

01-02-2017
01-09-2017
01-16-2017
01-23-2017
01-30-2017
02-06-2017

我想创建一个存储过程,它将在给定一天的日期范围之间插入日期

CREATE sp_InsertReservation
    (@DateFrom date,
     @DateTo date,
     @Day)
AS 
BEGIN
    --A Loop through @DateFrom and @DateTo getting the date given the day
    BEGIN
        INSERT INTO Reservation(...DayDate...) 
        VALUES (...[date that was on the given day]...)
    END
END

SQL Server 2012及更低版本

1 个答案:

答案 0 :(得分:3)

我经常使用TVF创建动态日期范围。您提供所需的范围,DatePart和增量。 Tally / Numbers表甚至是日历表都可以解决这个问题

示例

Select *
 From  [dbo].[udf-Range-Date] ('2017-01-01','2017-02-06','DD',1)
 Where DateName(DW,retval) = 'Monday'

<强>返回

RetSeq  RetVal
2       2017-01-02 00:00:00.000
9       2017-01-09 00:00:00.000
16      2017-01-16 00:00:00.000
23      2017-01-23 00:00:00.000
30      2017-01-30 00:00:00.000
37      2017-02-06 00:00:00.000

UDF

CREATE FUNCTION [dbo].[udf-Range-Date] (@R1 datetime,@R2 datetime,@Part varchar(10),@Incr int)
Returns Table
Return (
    with cte0(M)   As (Select 1+Case @Part When 'YY' then DateDiff(YY,@R1,@R2)/@Incr When 'QQ' then DateDiff(QQ,@R1,@R2)/@Incr When 'MM' then DateDiff(MM,@R1,@R2)/@Incr When 'WK' then DateDiff(WK,@R1,@R2)/@Incr When 'DD' then DateDiff(DD,@R1,@R2)/@Incr When 'HH' then DateDiff(HH,@R1,@R2)/@Incr When 'MI' then DateDiff(MI,@R1,@R2)/@Incr When 'SS' then DateDiff(SS,@R1,@R2)/@Incr End),
         cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cte2(N)   As (Select Top (Select M from cte0) Row_Number() over (Order By (Select NULL)) From cte1 a, cte1 b, cte1 c, cte1 d, cte1 e, cte1 f, cte1 g, cte1 h ),
         cte3(N,D) As (Select 0,@R1 Union All Select N,Case @Part When 'YY' then DateAdd(YY, N*@Incr, @R1) When 'QQ' then DateAdd(QQ, N*@Incr, @R1) When 'MM' then DateAdd(MM, N*@Incr, @R1) When 'WK' then DateAdd(WK, N*@Incr, @R1) When 'DD' then DateAdd(DD, N*@Incr, @R1) When 'HH' then DateAdd(HH, N*@Incr, @R1) When 'MI' then DateAdd(MI, N*@Incr, @R1) When 'SS' then DateAdd(SS, N*@Incr, @R1) End From cte2 )

    Select RetSeq = N+1
          ,RetVal = D 
     From  cte3,cte0 
     Where D<=@R2
)
/*
Max 100 million observations -- Date Parts YY QQ MM WK DD HH MI SS
Syntax:
Select * from [dbo].[udf-Range-Date]('2016-10-01','2020-10-01','YY',1) 
Select * from [dbo].[udf-Range-Date]('2016-01-01','2017-01-01','MM',1) 
*/