Get a list of dates between two dates using a function

前端 未结 21 1429
天涯浪人
天涯浪人 2020-11-22 06:25

My question is similar to this MySQL question, but intended for SQL Server:

Is there a function or a query that will return a list of days between two dates? For exa

21条回答
  •  我寻月下人不归
    2020-11-22 06:51

    Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:

    CREATE TABLE Numbers
    (Number int  NOT NULL,
        CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    DECLARE @x int
    SET @x=0
    WHILE @x<8000
    BEGIN
        SET @x=@x+1
        INSERT INTO Numbers VALUES (@x)
    END
    

    here is the function:

    CREATE FUNCTION dbo.ListDates
    (
         @StartDate    char(10)  
        ,@EndDate      char(10)
    )
    RETURNS
    @DateList table
    (
        Date datetime
    )
    AS
    BEGIN
    
    
    IF ISDATE(@StartDate)!=1 OR ISDATE(@EndDate)!=1
    BEGIN
        RETURN
    END
    
    INSERT INTO @DateList
            (Date)
        SELECT
            CONVERT(datetime,@StartDate)+n.Number-1
            FROM Numbers  n
            WHERE Number<=DATEDIFF(day,@StartDate,CONVERT(datetime,@EndDate)+1)
    
    
    RETURN
    
    END --Function
    

    use this:

    select * from dbo.ListDates('2010-01-01', '2010-01-13')
    

    output:

    Date
    -----------------------
    2010-01-01 00:00:00.000
    2010-01-02 00:00:00.000
    2010-01-03 00:00:00.000
    2010-01-04 00:00:00.000
    2010-01-05 00:00:00.000
    2010-01-06 00:00:00.000
    2010-01-07 00:00:00.000
    2010-01-08 00:00:00.000
    2010-01-09 00:00:00.000
    2010-01-10 00:00:00.000
    2010-01-11 00:00:00.000
    2010-01-12 00:00:00.000
    2010-01-13 00:00:00.000
    
    (13 row(s) affected)
    

提交回复
热议问题