检索日期SQL Server

时间:2014-07-11 20:43:13

标签: sql sql-server

我想知道是否有办法检索SQL Server中所有日期的列表。我知道使用getdate()函数将检索当前的日期和时间。是否有任何函数会返回所有日期的列表?

2 个答案:

答案 0 :(得分:3)

不是来自内置函数,不是,但您可以创建自己的function来执行此操作。

您可以通过以下方式生成日期列表:

Declare @FromDate   Date = '2014-04-21',
        @ToDate     Date = '2014-05-02'

;With Date (Date) As
(
    Select  @FromDate Union All
    Select  DateAdd(Day, 1, Date)
    From    Date
    Where   Date < @ToDate
)
Select  Date
From    Date
Option  (MaxRecursion 0)

使用此逻辑,您可以创建自己的function来执行相同操作:

Create Function udf_GenerateDateRange(@From Date, @To Date)
Returns @Date Table
(
    Date Date
)
As Begin

    ;With Date (Date) As
    (
        Select  @From Union All
        Select  DateAdd(Day, 1, Date)
        From    Date
        Where   Date < @To
    )
    Insert  @Date
    Select  Date
    From    Date
    Option  (MaxRecursion 0)

    Return
End

使用function,您可以通过以下方式选择日期范围内的所有内容:

Select * From udf_GenerateDateRange( '2014-01-01', '2014-05-10' )

我不知道你所说的“所有日期”是什么意思,但你应该能够传递一个开始和结束日期,它将返回中间的所有内容。

答案 1 :(得分:3)

此功能将以指定的频率为您提供从开始到结束的日期列表。

IF OBJECT_ID('ListDates') IS NOT NULL DROP FUNCTION ListDates
GO

CREATE FUNCTION [dbo].[ListDates]
/* 
    returns a list of intervals with the given frequency that start after @StartDate and 
    before @EndDate. 
*/
(
    @Frequency int, 
    @StartDate DateTime, 
    @EndDate DateTime)
/*
    @Frequency: 
        0 - day, 
        1 - week, 
        2 - month
        3 - 3 months
        4 - 6 months
        5 - year
*/
returns @List TABLE (StartRange Date, EndRange Date)
BEGIN
    with dates as (
      SELECT cast(@StartDate as Date) [date]
      UNION ALL
      SELECT 
        CASE @Frequency
            WHEN 0 THEN DATEADD(day,1,t.date)
            WHEN 1 THEN DATEADD(week,1,t.date)
            WHEN 2 THEN DATEADD(month,1,t.date)
            WHEN 3 THEN DATEADD(month,3,t.date)
            WHEN 4 THEN DATEADD(month,6,t.date)
            WHEN 5 THEN DATEADD(year,1,t.date)
        END
      FROM dates t
      WHERE t.[date] < @EndDate
    )
    insert into @List (StartRange, EndRange)
    select 
        [Date],
        CASE @Frequency
            WHEN 0 THEN DATEADD(day,1,[Date])
            WHEN 1 THEN DATEADD(week,1,[Date])
            WHEN 2 THEN DATEADD(month,1,[Date])
            WHEN 3 THEN DATEADD(month,3,[Date])
            WHEN 4 THEN DATEADD(month,6,[Date])
            WHEN 5 THEN DATEADD(year,1,[Date])
        END
    from dates
    WHERE [Date] < @EndDate
    OPTION (MAXRECURSION 10000)
    RETURN
END
GO