Deterministic scalar function to get week of year for a date

半腔热情 提交于 2019-12-20 02:52:27

问题


Here is a great way of how to get day of week for a date, Deterministic scalar function to get day of week for a date.

Now, could anyone help me to create a deterministic scalar function to get week of year for a date please? Thanks.


回答1:


This works deterministically, I can use it as a computed column.

datediff(week, dateadd(year, datediff(year, 0, @DateValue), 0), @DateValue) + 1 

Test code:

;
with 
Dates(DateValue) as 
(
    select cast('2000-01-01' as date)
    union all 
    select dateadd(day, 1, DateValue) from Dates where DateValue < '2050-01-01'
)
select 
    year(DateValue) * 10000 + month(DateValue) * 100 + day(DateValue) as DateKey, DateValue,        
    datediff(day, dateadd(week, datediff(week, 0, DateValue), 0), DateValue) + 2 as DayOfWeek,
    datediff(week, dateadd(month, datediff(month, 0, DateValue), 0), DateValue) + 1 as WeekOfMonth,
    datediff(week, dateadd(year, datediff(year, 0, DateValue), 0), DateValue) + 1 as WeekOfYear
    from Dates option (maxrecursion 0)


来源:https://stackoverflow.com/questions/11432719/deterministic-scalar-function-to-get-week-of-year-for-a-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!