Check if a date range has a weekend
One way, just showing you how you can use a table of numbers for this
declare @start datetime;
set @start = '2013-06-14';
declare @end datetime;
set @end = '2013-06-15'; -- play around by making this 2013-06-14 and other dates
IF EXISTS (SELECT * FROM(
SELECT DATEADD(dd,number,@start) AS SomeDAte
FROM master..spt_values
WHERE type = 'P'
AND DATEADD(dd,number,@start) BETWEEN @start AND @end) x
WHERE DATEPART(dw,SomeDate) IN(1,7)) -- US assumed here
SELECT 'Yes'
ELSE
SELECT 'No'
Example to return all weekends between two dates
declare @start datetime;
set @start = '2013-06-14';
declare @end datetime;
set @end = '2013-06-30';
SELECT DATEADD(dd,number,@start) AS SomeDAte
FROM master..spt_values
WHERE type = 'P'
AND DATEADD(dd,number,@start) BETWEEN @start AND @end
AND DATEPART(dw,DATEADD(dd,number,@start)) IN(1,7)
Results
2013-06-15 00:00:00.000
2013-06-16 00:00:00.000
2013-06-22 00:00:00.000
2013-06-23 00:00:00.000
2013-06-29 00:00:00.000
2013-06-30 00:00:00.000
You have a weekend day if any one of the following three conditions is true:
The day of week (as an integer) of the end date is less than the day of week of the start date
Either day is itself a weekend day
The range includes at least six days
.
select
Coalesce(
--rule 1
case when datepart(dw,@end) - datepart(dw,@start) < 0 then 'Weekend' else null end,
-- rule 2
-- depends on server rules for when the week starts
-- I think this code uses sql server defaults
case when datepart(dw,@end) in (1,7) or datepart(dw,@start) in (1,7) then 'Weekend' else null end,
--rule 3
-- six days is long enough
case when datediff(d, @start, @end) >= 6 then 'Weekend' Else null end,
-- default
'Weekday')
I have a function that calculates working days between 2 dates, the basic query is
declare @start datetime;
set @start = '2013-06-14';
declare @end datetime;
set @end = '2013-06-17';
SELECT
(DATEDIFF(dd, @Start, @end) +1) -- total number of days (inclusive)
-(DATEDIFF(wk, @Start, @end) * 2) -- number of complete weekends in period
-- remove partial weekend days, ie if starts on sunday or ends on saturday
-(CASE WHEN DATENAME(dw, @Start) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @end) = 'Saturday' THEN 1 ELSE 0 END)
so you could work out if dates include weekend if working days different to datediff in days
SELECT case when (DATEDIFF(dd, @Start, @end) +1) <>
(DATEDIFF(dd, @Start, @end) +1) -- total number of days (inclusive)
-(DATEDIFF(wk, @Start, @end) * 2) -- number of complete weekends in period
-- remove partial weekend days, ie if starts on sunday or ends on saturday
-(CASE WHEN DATENAME(dw, @Start) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @end) = 'Saturday' THEN 1 ELSE 0 END) then 'Yes' else 'No' end as IncludesWeekends
or simpler
SELECT (DATEDIFF(wk, @Start, @end) * 2) +(CASE WHEN DATENAME(dw, @Start) = 'Sunday' THEN 1 ELSE 0 END) +(CASE WHEN DATENAME(dw, @end) = 'Saturday' THEN 1 ELSE 0 END) as weekendDays