如何在sql server中获取两个日期之间的所有日期

时间:2015-05-04 10:02:16

标签: sql sql-server sql-server-2008 tsql

我希望获得startendEnddate之间的所有日期。我用它来获得所需的结果。但是函数跳过了当前日期。

Declare @StartDate Datetime  ='2014-04-01 11:13:37'
               ,@EndDate datetime ='2014-04-04 11:13:37'

查询: -

Select * from table where date between @Startdate and @EndDate

当前结果: -

2014-04-02 11:13:37
2014-04-03 11:13:37
2014-04-04 11:13:37

预期结果: -

2014-04-01 11:13:37
2014-04-02 11:13:37
2014-04-03 11:13:37
2014-04-04 11:13:37

3 个答案:

答案 0 :(得分:1)

你可以创建一个这样的程序:

var settings = (typeof options.theme[theme] != 'undefined')
            ? options.theme[theme]
            : options.theme['simple'];

settings.external_plugins = settings.external_plugins || {};

礼貌:Find All the Days Between Two Dates

答案 1 :(得分:0)

你可以尝试这个

Declare @StartDate Date  ='2014-04-01'
               ,@EndDate date ='2014-04-04'

                  (OR)

Declare @StartDate Datetime  ='2014-04-01  00:00:00'
               ,@EndDate datetime ='2014-04-04  12:59:59'

查询: -

Select * from table where date between @Startdate and @EndDate

答案 2 :(得分:0)

您的查询非常适合我。

DECLARE @StartDate DATETIME = '2014-04-01 11:13:37',
        @EndDate   DATETIME = '2014-04-04 11:13:37';

WITH cte_dates
AS
(
    SELECT DATEADD(MONTH,-1,@startDate) dates --get dates from a month before start date
    UNION ALL
    SELECT DATEADD(DAY,1,dates)
    FROM cte_dates
    WHERE dates < DATEADD(MONTH,1,@EndDate) --up to a month after end date
)

SELECT dates
FROM cte_dates 
WHERE dates BETWEEN @Startdate AND @EndDate

结果:

dates
-----------------------
2014-04-01 11:13:37.000
2014-04-02 11:13:37.000
2014-04-03 11:13:37.000
2014-04-04 11:13:37.000

这意味着它可能是您的数据的问题,特别是时间部分。如果您不需要查看时间并且只需要特定日期,请尝试以下方法:

DECLARE @StartDate DATE = '2014-04-01',
        @EndDate   DATE = '2014-04-04';

SELECT *
FROM yourTable
WHERE CAST([date] AS DATE) BETWEEN @startDate AND @EndDate