months between two dates in sql server with starting and end date of each of them in sql server

前端 未结 6 1461
误落风尘
误落风尘 2020-12-20 00:07

i want to get months between two dates with their starting and end dates.Suppose if i enter startdate as \"2017-04-01\" and enddate as \"2017-07-31\", i want list of months

6条回答
  •  情书的邮戳
    2020-12-20 00:42

    I created a stored procedure for that, may be you can convert that into user defined Function. Posting that code below,

    create procedure ListMonths
    @date1 date,@date2 date 
    as
    begin
    create Table #tempTable
    (mnth varchar(10))
    while @date1<@date2
    begin
    insert into #tempTable
    select DATENAME(month,@date1)
    set @date1 = DATEADD(MONTH,1,@date1)
    end
    select * from #tempTable;
    drop table #tempTable;
    end
    

    To execute the stored procedure:

    exec ListMonths '2017-04-01','2018-01-31'
    

    output

    +------------+
    |   mnth     |
    +------------+
    | April      |
    | May        | 
    | June       |
    | July       |
    | August     |
    | September  |
    | October    |
    | November   |
    | December   |
    | January    |
    +------------+
    

    result

提交回复
热议问题