Home > Database > Mysql Tutorial > How to Generate a List of Dates Between Two Dates in MySQL and SQL Server?

How to Generate a List of Dates Between Two Dates in MySQL and SQL Server?

Barbara Streisand
Release: 2025-01-22 04:42:08
Original
340 people have browsed it

How to Generate a List of Dates Between Two Dates in MySQL and SQL Server?

Generate a list of dates between two dates

MySQL provides standard functions to retrieve a list of dates within a specified date range. The steps are as follows:

1. Create stored procedure:

Create a stored procedure to generate the required date range. make_intervals Stored procedures can create different types of intervals, including days, minutes, and seconds.

2. Process code:

<code class="language-sql">CREATE PROCEDURE make_intervals(
    startdate timestamp, 
    enddate timestamp, 
    intval integer, 
    unitval varchar(10)
)
BEGIN
    -- ... (存储过程代码,请参考答案中的完整代码)
END;</code>
Copy after login

3. Sample interval generation:

To generate a list of dates between 2009-01-01 and 2009-01-10, execute the following command:

<code class="language-sql">call make_intervals('2009-01-01 00:00:00', '2009-01-10 00:00:00', 1, 'DAY');</code>
Copy after login

4. Connect with your data:

Join the generated date range (located in the time_intervals temporary table) with your data table to aggregate the data as needed.

Example data scenario:

Similarly, you can create a function for SQL Server. This function produces results similar to those mentioned in the question:

<code class="language-sql">CREATE FUNCTION GetDateList(@StartDate DATETIME, @EndDate DATETIME, @Interval INT, @Unit VARCHAR(10))
RETURNS TABLE
AS
BEGIN
    DECLARE @ThisDate DATETIME = @StartDate;
    WHILE @ThisDate <= @EndDate
    -- ... (函数代码,请参考答案中的完整代码)
END;</code>
Copy after login

The above is the detailed content of How to Generate a List of Dates Between Two Dates in MySQL and SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template