Stored Procedure to return months specified by parameter

  • Need a stored procedure to return months. For example,

    procedure 1, 5 should return 1st month i.e January through next 5 months including january

    1 january

    2 febraury

    3 march

    4 april

    5 may

    procedure 2, 4 should return

    2 febraury

    3 march

    4 april

    5 may

    Also, for procedure 10, 5 should return

    10 october

    11 november

    12 december

    1 january

    2 febraury

    like a cycle. hope you get the idea. Please help

    Thanks

  • declare @from_month int

    declare @months int

    select @from_month = 6, @months = 11

    set nocount on

    declare @t table (num int not null primary key clustered)

    insert into @t

    -- Just a quick and dirty number table

    select top (@months) row_number() over (order by id) from syscolumns

    select

    [Month] = num+@from_month-1,

    [MonthName] = datename(month,dateadd(month,num+@from_month-2,0))

    from

    @t

    order by

    1

    Results:

    Month MonthName

    ----------- ------------------------------

    6 June

    7 July

    8 August

    9 September

    10 October

    11 November

    12 December

    13 January

    14 February

    15 March

    16 April

  • thanks a lot for that. it works well except for the part where it shows month as 13 for january and 14 for febraury and so on. it wud be nice if it showed 1 for jan and 2 for feb...

  • Hi

    Just take Michael Valentine Jones's fine sample and change the from_month to another value or use something like "DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)" to remove everything but the year/month of a specified date.

    Greets

    Flo

  • fuzzy528 (10/30/2009)


    thanks a lot for that. it works well except for the part where it shows month as 13 for january and 14 for febraury and so on. it wud be nice if it showed 1 for jan and 2 for feb...

    ...

    select

    [Month] = ((num+@from_month-2)%12)+1,

    ...

  • Yes it works fine. Thanks a lot Cheers

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply