• Cadavre (12/3/2012)


    CREATE TABLE #yourTempTable([MonthName] VARCHAR(9), [Year] INT);

    WITH CTE(N) AS (SELECT 1 FROM (SELECT 1 UNION ALL SELECT 1)a(N)),

    CTE2(N) AS (SELECT 1 FROM CTE x CROSS JOIN CTE y),

    CTE3(N) AS (SELECT 1 FROM CTE2 x CROSS JOIN CTE2 y),

    TALLY(N) AS (SELECT 0 UNION ALL

    SELECT TOP 11 ROW_NUMBER() OVER(ORDER BY (SELECT NULL))

    FROM CTE3),

    DATETALLY(N) AS (SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE())+N, 0)

    FROM TALLY)

    INSERT INTO #yourTempTable

    SELECT DATENAME(month,N), YEAR(N)

    FROM DATETALLY;

    SELECT *

    FROM #yourTempTable;

    Jeff Moden would probably be disappointed with me if I didn't post this somewhat terser version:

    SELECT Month=DATENAME(month, MyDate), Year=DATEPART(year, MyDate)

    FROM [master].dbo.spt_values Tally

    CROSS APPLY (

    SELECT DATEADD(month, number-1, GETDATE())) a (MyDate)

    WHERE [Type] = 'P' AND Number BETWEEN 1 AND 12


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St