[MSSQL]当月第一个周六

群里的朋友(广东-白河一漂)有个需求取得当月的第一个周六

写了一个函数实现:

-- =============================================      
-- Author: <David Gong>      
-- Create date: <2013-03-27>      
-- Description: <当月第一个周六>      
-- ============================================= 
Create function [dbo].[CurMonthFirstWeekEnd]
(
	@CurrentDate DateTime
)returns NVARCHAR(10)
as 
begin
 
DECLARE @StarDay  DateTime ,@EndDay  DateTime , @week NVARCHAR(10),@adddays INT,@mydate as NVARCHAR(MAX)
SELECT @adddays=1
select  @StarDay= dateadd(d,-day(@CurrentDate)+1,@CurrentDate)
select  @EndDay=dateadd(d,-day(@CurrentDate),dateadd(m,1,@CurrentDate))
WHILE convert(char(8),@StarDay,112)<=convert(char(8),@EndDay,112)
BEGIN 
    SELECT @week=DATENAME(dw,@StarDay)
    set @StarDay=@StarDay+@adddays
    if(@week='星期五')
    begin
    SET @mydate=convert(char(10),@StarDay,120)   
    break;
    end
END
return @mydate 
end

 
select dbo.[CurMonthFirstWeekEnd]('2013-01-25')
select dbo.[CurMonthFirstWeekEnd]('2013-01-01')
select dbo.[CurMonthFirstWeekEnd]('2013-02-22')
select dbo.[CurMonthFirstWeekEnd]('2013-03-28')
select dbo.[CurMonthFirstWeekEnd]('2013-04-03')


中间判断星期五,是因为先加了1,欢迎拍砖

 

你可能感兴趣的:([MSSQL]当月第一个周六)