Question

I have a YearMonths table where ever year requires 12 entries, one for each month, i.e.,

Year  Month
2013    1
2013    2
...
2013   12

For each new year, I have to generate 12 new records. I know I can do this with a loop, but I'm trying to figure out a way to do it without one. I want to fill the table by selecting all of the years from a Years table and going from there, I'm just not sure how without using a loop.

Was it helpful?

Solution

Assuming that your YEARS table is something like this:

CREATE TABLE YEARS(Year INT) 

And your YearMonths table is something like this:

CREATE TABLE YearMonths(Year INT, Month Int)

You can do something like this:

WITH CTE AS (
        SELECT 1 AS Mnth
        UNION ALL
        SELECT Mnth + 1 FROM CTE
        WHERE Mnth < 12)
INSERT INTO YearMonths (Year, Month)
SELECT Year, Mnth FROM YEARS CROSS APPLY CTE
ORDER BY Year, Mnth

This approach uses a recursive Common Table Expression (available since SQL Server 2005) to build list of integer 1-12 and then cross applies it to Years table to build final list.

Demo: http://sqlfiddle.com/#!3/bbb0f/1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top