简体   繁体   中英

Get month name with different month start and end dates

Getting the month for the current date is, obviously, straight forward, but I'm needing to get the month name with a different end date.

I need to get the month name with the start date of the month being the first Thursday after the first Wednesday of the month and the end date of the month being the first Wednesday of the following month. It's for an accounting thing, so I'm not going to argue with the spec!

eg for 2014, January would run from 9th Jan - 5th Feb, February would run from 6th February - 5th March, March would run from 6th March - 2nd April.

I would suggest that you create a table with your 'accounting months' in it, having a start date, end date and month name columns.

You could then query this to find the row where your date is between the start and end dates and return the month name. Putting this into a scalar function would then allow it to be reusable and relatively easily updated for next years months as well.

I think, as per Paddy's answer , a lookup table is the simplest thing to do. Here's one way to generate the rows for it:

; With Numbers(n) as (
    select 4 union all select 5
), Months as (
    select CONVERT(date,'20010104') as StartDt,CONVERT(date,'20010207') as EndDt,
           DATENAME(month,'20010103') as Month
    union all
    select DATEADD(week,n1.n,StartDt),DATEADD(week,n2.n,EndDt),
           DATENAME(month,DATEADD(week,n1.n,StartDt))
    from Months,Numbers n1,Numbers n2 --Old-skool join, just for once
    where DATEPART(day,DATEADD(week,n1.n,StartDt)) between 2 and 8 and
          DATEPART(day,DATEADD(week,n2.n,EndDt)) between 1 and 7 and
          StartDt < '21000101'
)
select * from Months option (maxrecursion 0)

(CW since this is effectively just an extension to Paddy's answer but I don't want to edit their answer, nor is it suitable for a comment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM