确定性标量函数,以获取日期的一年中的一周

时间:2012-07-11 12:31:13

标签: sql-server user-defined-functions

以下是如何为日期Deterministic scalar function to get day of week for a date获取星期几的好方法。

现在,有人可以帮我创建一个确定性的标量函数来获得一年中的日期吗?感谢。

1 个答案:

答案 0 :(得分:3)

这确实有效,我可以将它用作计算列。

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

测试代码:

;
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)