• mw_sql_developer - Friday, March 23, 2018 3:03 PM

    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!

    Heh... why would you ever think that I didn't run your code? 😉  I'm the guy that wrote the article that says to do so.

    You say you want the month start date but then you return the start of the date range defined by the variable instead of the start of the mode.  So, if the date in the @VEndDate variable contains '2018-12-15' do you want to return '2018-12-15' or '2018-12-31'?

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)