SQL Server 統計某個月週末的天數
阿新 • • 發佈:2018-11-17
---注意:這裡統計的週末包括周5,周6,但不包括週日
ALTER FUNCTION [dbo].[GetWeekDaysByMonth] ( @Year INT, @Month INT, @Day INT ) RETURNS INT AS BEGIN DECLARE @date DATETIME = DATEFROMPARTS(@Year, @Month, 28); DECLARE @weekday INT = 0, @weekDays INT = 0, @daysCount INT =0, @dayDiff INT = 0; SET @daysCount = 32- DAY(DATETIMEFROMPARTS(@Year, @Month, @Day, 1, 1, 1, 1)- DAY(DATETIMEFROMPARTS(@Year, @Month, @Day, 1, 1, 1, 1)) + 32); --月天數 SET @dayDiff = @daysCount - 28; IF @@DATEFIRST = 7 BEGIN SET @weekday = 7 - (8 - DATEPART(WEEKDAY, @date)) % 7;---周幾 END; ELSE BEGIN SET @weekday = DATEPART(WEEKDAY, @date);---周幾 END; WHILE @dayDiff > 0 BEGIN IF (@weekday + @dayDiff = 5 OR @weekday + @dayDiff = 6)--判斷是否週五,週六 (如果是判斷週六週日的天數,條件改為6和7) SET @weekDays = @weekDays + 1;SET @dayDiff = @dayDiff - 1; END; --SELECT dbo.GetWeekDaysByMonth56(2018,11,25) --SELECT dbo.GetWeekDaysByMonth56(2018,11,26) RETURN @weekDays+8;---每個月28天裡的週末有8天 END;