我创建了 2 个函数来处理这个问题 1)获取一周的第一天或最后一天 2)获取周数或年份
功能一
CREATE FUNCTION [dbo].[fn_GetDayOf]
(
@Date datetime,
--@FirstDayOfWeek int = 7,
@Mode int =1
)
/*
Mode 1: First Day Of Week
Mode 2: Last Day Of Week
*/
RETURNS datetime
WITH EXECUTE AS CALLER
BEGIN
Declare @Return datetime
--SET DATEFIRST @FirstDayOfWeek
IF @Mode = 1
BEGIN
select @Return = dateadd(day,-(datepart(weekday,@date)-1),convert(date,@date))
END
ELSE IF @Mode = 2
BEGIN
select @Return = dateadd(SECOND,-1,convert(datetime,dateadd(day,(datepart(weekday,@date)),convert(date,@date))))
END
ELSE
BEGIN
SET @Return = @Date
END
--SET DATEFIRST 7
RETURN @Return
END
功能二
CREATE FUNCTION [dbo].[fn_GetYearWeek]
(
@Date datetime,
--@FirstDayOfWeek int = 7,
@Mode int =1
)
/*
Mode 1 = Week Number
Mode 2 = Year
*/
RETURNS INT
BEGIN
declare @Return int
IF @Mode = 1
BEGIN
select @Return = case when datepart(week,[dbo].[fn_GetDayOf] (@Date,1)) <> datepart(week,[dbo].[fn_GetDayOf] (@Date,2)) then datepart(week,[dbo].[fn_GetDayOf] (@Date,1)) else datepart(week,[dbo].[fn_GetDayOf] (@Date,2)) end
END
ELSE IF @Mode = 2
BEGIN
select @Return = case when datepart(WEEK,[dbo].[fn_GetDayOf] (@Date,1)) <> datepart(week,[dbo].[fn_GetDayOf] (@Date,2)) then datepart(YEAR,[dbo].[fn_GetDayOf] (@Date,1)) else datepart(YEAR,[dbo].[fn_GetDayOf] (@Date,2)) end
END
ELSE
BEGIN
SET @Return = -1
END
Return @Return
END
运行示例
declare @T table (dt datetime)
insert into @T values
('2010-12-25'),
('2010-12-26'),
('2010-12-27'),
('2010-12-28'),
('2010-12-29'),
('2010-12-30'),
('2010-12-31'),
('2011-01-01'),
('2011-01-02'),
('2011-01-03'),
('2011-01-04'),
('2011-01-05'),
('2011-01-06'),
('2011-01-07'),
('2011-01-08'),
('2011-12-31'),
('2012-01-01'),
('2012-01-02'),
('2012-12-31'),
('2013-01-01')
select
dt,
datepart(week,dt),
--case when datepart(week,[dbo].[fn_GetDayOf] (dt,1)) <> datepart(week,[dbo].[fn_GetDayOf] (dt,2)) then datepart(week,[dbo].[fn_GetDayOf] (dt,1)) else datepart(week,[dbo].[fn_GetDayOf] (dt,2)) end
[dbo].[fn_GetYearWeek] (dt,1),
[dbo].[fn_GetYearWeek] (dt,2)
from @T
结果: