The original reprint link cannot be found.
The following question reproduces the content:
The first:
-- Get the week of the month that the current date is --Test: select dbo.getMonthWeek(getdate()) Result: 2nd week of October CREATE function [dbo].[getMonthWeek](@d datetime) returns varchar(20) as begin declare @returns varchar(20), @monthfirstDay datetime, @firstMondy datetime select @monthfirstDay=left(convert(varchar,@d,23),7)+'-01' if not exists(select 1 from master.dbo.spt_values where type=N'P' and number between 0 and datediff(d,@monthfirstDay,@d) and datepart(dw,dateadd(d,number,@monthfirstDay))=2) begin select @monthfirstDay=dateadd(mm,-1,@monthfirstDay) end ;with t as(select 'days'=dateadd(d,number,@monthfirstDay) from master.dbo.spt_values where type=N'P' and number<=7) select @firstMondy=min([days]) from t where datepart(dw,[days])=2 select @returns=rtrim(datepart(mm,@monthfirstDay))+'月的第'+rtrim(datediff(d,@firstMondy,@d)/7+1)+'周' return @returns end
The second:
-- Get the week of the month that the current date is --Test: select dbo.WeekOfMonth(getDate()); result: 2 CREATE FUNCTION [dbo].[WeekOfMonth](@day datetime) RETURNS int AS begin ----declare @day datetime declare @num int declare @Start datetime declare @dd int declare @dayofweek char(8) declare @dayofweek_num char(8) declare @startWeekDays int ---set @day='2009-07-05' if datepart(dd,@day)=1 return 1 else set @Start= (SELECT DATEADD(mm, DATEDIFF(mm,0,@day), 0)) -- the first day of a month set @dayofweek= (datename(weekday, @Start)) --- get the day of the week on the first day of the month set @dayofweek_num=(select (case @dayofweek when 'Monday' then 2 when 'Tuesday' then 3 when 'Wednesday' then 4 when 'Thursday' then 5 when 'Friday' then 6 when 'Saturday' then 7 when 'Sunday' then 1 end)) set @dayofweek_num= 7-@dayofweek_num+1 --- get the number of days on the first Monday of the month ---print @dayofweek_num set @dd=datepart(dd,@day) ---- get today is the day of the month --print @dd if @dd<=@dayofweek_num -- less than the number of days in the previous week return 1 else set @dd=@dd-@dayofweek_num if @dd % 7=0 begin set @num=@dd / 7 return @num+1 end else --if @dd % 7<>0 set @num=@dd / 7 set @num=@num+1+1 return @num end