如何列出两个日期之间的所有日期

时间:2013-07-08 14:58:16

标签: sql-server stored-procedures

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

例如:

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

结果:

2015-05-29
2015-05-30

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

此致

5 个答案:

答案 0 :(得分:34)

您可以使用数字表:

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 ║
╚════════════╝

答案 1 :(得分:25)

使用此,

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)

答案 2 :(得分:17)

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

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 Fiddle with demo

或者最好还是创建一个日历表,然后从中选择。

答案 3 :(得分:1)

我使用以下方式制作日历:

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

然后一个Store程序传递两个日期,那就是全部:

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;

答案 4 :(得分:1)

您可以创建传递2个日期的存储过程

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