--建立函数计算星期 create function w_count( @ym varchar(6) --月份 ,@dw varchar(8))--星期几 returns int as begin declare @count_day int = 0 declare @b datetime = cast(@ym + '01' as datetime) declare @e datetime = cast(dateadd(dd,-1,dateadd(MM,1,@ym + '01')) as datetime) while(@b <= @e) begin if(DATENAME(DW,@b) = @dw) begin set @count_day = @count_day + 1 end set @b = DATEADD(DD,1,@b) end return(@count_day) end go --测试 select dbo.w_count('201405','星期六')