Get a list of dates between two dates

后端 未结 20 2104
醉梦人生
醉梦人生 2020-11-22 00:26

Using standard mysql functions is there a way to write a query that will return a list of days between two dates.

eg given 2009-01-01 and 2009-01-13 it would return

20条回答
  •  盖世英雄少女心
    2020-11-22 00:53

    I would use something similar to this:

    DECLARE @DATEFROM AS DATETIME
    DECLARE @DATETO AS DATETIME
    DECLARE @HOLDER TABLE(DATE DATETIME)
    
    SET @DATEFROM = '2010-08-10'
    SET @DATETO = '2010-09-11'
    
    INSERT INTO
        @HOLDER
            (DATE)
    VALUES
        (@DATEFROM)
    
    WHILE @DATEFROM < @DATETO
    BEGIN
    
        SELECT @DATEFROM = DATEADD(D, 1, @DATEFROM)
        INSERT 
        INTO
            @HOLDER
                (DATE)
        VALUES
            (@DATEFROM)
    END
    
    SELECT 
        DATE
    FROM
        @HOLDER
    

    Then the @HOLDER Variable table holds all the dates incremented by day between those two dates, ready to join at your hearts content.

提交回复
热议问题