How to populate a table with a range of dates?

后端 未结 10 1251
夕颜
夕颜 2020-11-22 04:24

I need a MySQL table to hold ALL DATES between 2011-01-01 and 2011-12-31. I have created a table with one column names \"_date\", type DATE.

With what query can I po

10条回答
  •  长情又很酷
    2020-11-22 05:01

    Try this:

    DROP PROCEDURE IF EXISTS filldates;
    DELIMITER |
    CREATE PROCEDURE filldates(dateStart DATE, dateEnd DATE)
    BEGIN
      WHILE dateStart <= dateEnd DO
        INSERT INTO tablename (_date) VALUES (dateStart);
        SET dateStart = date_add(dateStart, INTERVAL 1 DAY);
      END WHILE;
    END;
    |
    DELIMITER ;
    CALL filldates('2011-01-01','2011-12-31');
    

    Here's the SQL Fiddle to play with it: http://sqlfiddle.com/#!2/65d13/1

    EDIT (to check if date already exists) as asked by Andrew Fox.

    CREATE PROCEDURE filldates(dateStart DATE, dateEnd DATE)
    
    BEGIN
    
    DECLARE adate date;
    
        WHILE dateStart <= dateEnd DO
    
            SET adate = (SELECT mydate FROM MyDates WHERE mydate = dateStart);
    
            IF adate IS NULL THEN BEGIN
    
                INSERT INTO MyDates (mydate) VALUES (dateStart);
    
            END; END IF;
    
            SET dateStart = date_add(dateStart, INTERVAL 1 DAY);
    
        END WHILE;
    
    END;//
    

    Here's the SQL Fiddle to play with it: http://sqlfiddle.com/#!2/66f86/1

提交回复
热议问题