您可以使用以下功能。如果它从周末开始,第一个将给定的开始日期或结束日期移动到星期一(如果向后,则为星期五)。第二个计算没有周末的两个日期之间的秒数。然后你只需要检查总天数是否等于没有 weksends 的天数(下面的演示)。
CREATE FUNCTION [dbo].[__CorrectDate](
@date DATETIME,
@forward INT
)
RETURNS DATETIME AS BEGIN
IF (DATEPART(dw, @date) > 5) BEGIN
IF (@forward = 1) BEGIN
SET @date = @date + (8 - DATEPART(dw, @date))
SET @date = DateAdd(Hour, (8 - DatePart(Hour, @date)), @date)
END ELSE BEGIN
SET @date = @date - (DATEPART(dw, @date)- 5)
SET @date = DateAdd(Hour, (18 - DatePart(Hour, @date)), @date)
END
SET @date = DateAdd(Minute, -DatePart(Minute, @date), @date)
SET @date = DateAdd(Second, -DatePart(Second, @date), @date)
END
RETURN @date
END
GO
CREATE FUNCTION [dbo].[__DateDiff_NoWeekends](
@date1 DATETIME,
@date2 DATETIME
)
RETURNS INT AS BEGIN
DECLARE @retValue INT
SET @date1 = dbo.__CorrectDate(@date1, 1)
SET @date2 = dbo.__CorrectDate(@date2, 0)
IF (@date1 >= @date2)
SET @retValue = 0
ELSE BEGIN
DECLARE @days INT, @weekday INT
SET @days = DATEDIFF(d, @date1, @date2)
SET @weekday = DATEPART(dw, @date1) - 1
SET @retValue = DATEDIFF(s, @date1, @date2) - 2 * 24 * 3600 * ((@days + @weekday) / 7)
END
RETURN @retValue
END
然后你可以通过这种方式获取信息:
declare @start datetime
set @start = '20130614'
declare @end datetime
set @end = '20130615'
declare @daysTotal int
declare @daysWoWeekends int
SET @daysTotal = DATEDIFF(dd, @start, @end)
SET @daysWoWeekends = dbo.__DateDiff_NoWeekends(@start, @end) / (24 * 3600)
SELECT CASE WHEN @daysTotal = @daysWoWeekends
THEN 'No weekend between'
ELSE 'There are weeksends' END,
@daysTotal,
@daysWoWeekends,@start,@end
这是一个演示:http ://sqlfiddle.com/#!6/7cda7/11
There are weeksends 1 0 June, 14 2013 00:00:00+0000 June, 15 2013 00:00:00+0000