给一个年份,返回每月的第一个星期一

if object_id('fn_monday_of_month') is not null
drop function fn_monday_of_month
go

create function fn_monday_of_month(@year int)
returns @r table(dt datetime)
as
begin
declare @dt datetime,@i int
set @i=1
while @i<=12
begin
set @dt=ltrim(@year)+right('00'+ltrim(@i),2)+'01'
while 1=1
begin
insert @r select @dt where datepart(w,@dt+@@datefirst-1)=1
if datepart(w,@dt+@@datefirst-1)=1
break
set @dt=@dt+1
end
set @i=@i+1
end
return
end
go


--调用示例(返回2010年中每月第一个星期一)
select * from fn_monday_of_month(2010)
/*
dt
------------------------------------------------------
2010-01-04 00:00:00.000
2010-02-01 00:00:00.000
2010-03-01 00:00:00.000
2010-04-05 00:00:00.000
2010-05-03 00:00:00.000
2010-06-07 00:00:00.000
2010-07-05 00:00:00.000
2010-08-02 00:00:00.000
2010-09-06 00:00:00.000
2010-10-04 00:00:00.000
2010-11-01 00:00:00.000
2010-12-06 00:00:00.000

(所影响的行数为 12 行)
*/

你可能感兴趣的:(Go)