generate days from date range

后端 未结 29 2532
渐次进展
渐次进展 2020-11-21 05:19

I would like to run a query like

select ... as days where `date` is between \'2010-01-20\' and \'2010-01-24\'

And return data like:

29条回答
  •  自闭症患者
    2020-11-21 06:01

    DELIMITER $$
    CREATE PROCEDURE GenerateRangeDates(IN dateStart DATE, IN dateEnd DATE)
    BEGIN
    
        CREATE TEMPORARY TABLE IF NOT EXISTS dates (day DATE);
    
        loopDate: LOOP
            INSERT INTO dates(day) VALUES (dateStart); 
            SET dateStart = DATE_ADD(dateStart, INTERVAL 1 DAY);
    
            IF dateStart <= dateEnd 
                THEN ITERATE loopDate;
                ELSE LEAVE loopDate;
            END IF;
        END LOOP loopDate;
    
        SELECT day FROM dates;
        DROP TEMPORARY TABLE IF EXISTS dates;
    
    END 
    $$
    
    -- Call procedure
    call GenerateRangeDates( 
            now() - INTERVAL 40 DAY,
            now()
        );
    

提交回复
热议问题