• Jeff Moden - Friday, March 23, 2018 2:27 PM

    mw_sql_developer - Friday, March 23, 2018 10:09 AM


    Here is what I need. I have s start date and a end date.
    What I need is to break this down into several intervals ( monthly ) 
    So I was able to just get the very first interval.

    May you please help me get the rest of the intervals please.. I bet there is a stylish way to do this... instead of looping

    Select @VStartDate = '20170110';
    Select @VEndDate = '20171231';

    IF OBJECT_ID('tempdb..#MonthlyIntervals') IS NOT NULL
    DROP TABLE #MonthlyIntervals;

    CREATE TABLE #MonthlyIntervals( StartDt VARCHAR(8) , EndDt VARCHAR(8) );

    --INSERT INTO #MonthlyIntervals( StartDt , EndDt)

    With A as
    (
        Select @VStartDate as StartDt, CONVERT(CHAR(8),   DATEADD(MONTH, DATEDIFF(MONTH, -1, ((DateAdd(MM,1,@VStartDate ))     ))-1, -1), 112 ) as EndDt

    )
    Select * FROM A;

    Given your example dates, what are you expecting for the output?  I ask because it could me any of a different number of outputs based on the dates and your definition of a "monthly" interval.

    Run the code, you will see the output.  What I need is for each month in the span the month start date and end date. works beautifully!