Home >Database >Mysql Tutorial >How to Efficiently Populate a MySQL Table with a Date Range?
MySQL date range table filling method
When working with a MySQL database, you often need to generate and populate tables containing date ranges. This task would be very tedious if performed manually. This article introduces an efficient automation method.
Suppose we need to populate a MySQL table named "tablename" containing all dates between January 1, 2011 and December 31, 2011. The table has only one DATE type column called "_date".
We can use MySQL stored procedures to achieve:
<code class="language-sql">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');</code>
Here’s how the stored procedure works:
To avoid inserting duplicate dates, you can use the following modified version:
<code class="language-sql">CREATE PROCEDURE filldates(dateStart DATE, dateEnd DATE) BEGIN WHILE dateStart <= dateEnd DO IF NOT EXISTS (SELECT 1 FROM tablename WHERE _date = dateStart) THEN INSERT INTO tablename (_date) VALUES (dateStart); END IF; SET dateStart = date_add(dateStart, INTERVAL 1 DAY); END WHILE; END;</code>
This modification ensures that duplicate dates are not inserted into the table.
The above is the detailed content of How to Efficiently Populate a MySQL Table with a Date Range?. For more information, please follow other related articles on the PHP Chinese website!