Home > Database > Mysql Tutorial > How to Populate a Temporary Table with Dates Between Two Parameters?

How to Populate a Temporary Table with Dates Between Two Parameters?

Mary-Kate Olsen
Release: 2024-12-28 13:46:11
Original
852 people have browsed it

How to Populate a Temporary Table with Dates Between Two Parameters?

Populating Temp Table with Dates Between Parameters

To populate a temporary table with dates between and including two date parameters, including the first day of the month, consider the following approach:

Step 1: Create a Recursive Common Table Expression (CTE)

;WITH cte AS (
SELECT CASE WHEN DATEPART(Day,@StartDate) = 1 THEN @StartDate 
            ELSE DATEADD(Month,DATEDIFF(Month,0,@StartDate)+1,0) END AS myDate
UNION ALL
SELECT DATEADD(Month,1,myDate)
FROM cte
WHERE DATEADD(Month,1,myDate) <=  @EndDate
)
Copy after login

Step 2: Select Dates from CTE

SELECT myDate
FROM cte
OPTION (MAXRECURSION 0)
Copy after login

Example:

For @StartDate = '2011-01-01' and @EndDate = '2011-08-01', the following dates will be returned in the temporary table:

2011-01-01
2011-02-01
2011-03-01
2011-04-01
2011-05-01
2011-06-01
2011-07-01
2011-08-01
Copy after login

Note:

This approach handles cases where @StartDate is not the first day of the month by starting the recursion with the first of the next month. If you want to start with @StartDate regardless, remove the 1 from the inner SELECT statement in the CTE definition.

The above is the detailed content of How to Populate a Temporary Table with Dates Between Two Parameters?. 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