如何列出两个date之间的所有date

我想在SQL Server存储过程中的两个date之间列出date。

例如:

Date1: 2015-05-28 Date2: 2015-05-31 

结果:

 2015-05-29 2015-05-30 

如何计算两个给定date之间的所有date?

问候,

您可以使用数字表格:

 DECLARE @Date1 DATE, @Date2 DATE SET @Date1 = '20150528' SET @Date2 = '20150531' SELECT DATEADD(DAY,number+1,@Date1) [Date] FROM master..spt_values WHERE type = 'P' AND DATEADD(DAY,number+1,@Date1) < @Date2 

结果:

 ╔════════════╗ ║ Date ║ ╠════════════╣ ║ 2015-05-29 ║ ║ 2015-05-30 ║ ╚════════════╝ 

用这个,

 DECLARE @start_date DATETIME = '2015-02-12 00:00:00.000'; DECLARE @end_date DATETIME = '2015-02-13 00:00:00.000'; WITH AllDays AS ( SELECT @start_date AS [Date], 1 AS [level] UNION ALL SELECT DATEADD(DAY, 1, [Date]), [level] + 1 FROM AllDays WHERE [Date] < @end_date ) SELECT [Date], [level] FROM AllDays OPTION (MAXRECURSION 0) 

传递@start_date@end_date作为SP参数。

结果:

 Date level ----------------------- ----------- 2015-02-12 00:00:00.000 1 2015-02-13 00:00:00.000 2 (2 row(s) affected) 

创build一个类似于以下内容的存储过程:

 declare @startDate date; declare @endDate date; select @startDate = '20150528'; select @endDate = '20150531'; with dateRange as ( select dt = dateadd(dd, 1, @startDate) where dateadd(dd, 1, @startDate) < @endDate union all select dateadd(dd, 1, dt) from dateRange where dateadd(dd, 1, dt) < @endDate ) select * from dateRange 

SQL小提琴与演示 。

或者更好的是创build一个日历表,并从中select。

我做了一个日历,使用:

http://social.technet.microsoft.com/wiki/contents/articles/22776.t-sql-calendar-table.aspx

然后一个存储过程传递两个date,这就是所有:

 USE DB_NAME; GO CREATE PROCEDURE [dbo].[USP_LISTAR_RANGO_FECHAS] @FEC_INICIO date, @FEC_FIN date AS Select Date from CALENDARIO where Date BETWEEN @FEC_INICIO AND @FEC_FIN; 

您可以创build一个存储过程传递两个date

 CREATE PROCEDURE SELECTALLDATES ( @StartDate as date, @EndDate as date ) AS Declare @Current as date = DATEADD(DD, 1, @BeginDate); Create table #tmpDates (displayDate date) WHILE @Current < @EndDate BEGIN insert into #tmpDates VALUES(@Current); set @Current = DATEADD(DD, 1, @Current) -- add 1 to current day END Select * from #tmpDates drop table #tmpDates