One of my applications displays tables with some calculations about users working time. This is for corporate reporting. For this table I needed a way to find how many weekends days are in given month. As most of calculation work is done in SQL Server stored procedure I decided to keep stuff there and found a way how to get weekend days with common table expression.
I looked for different options and in given solution it seemed the best idea to go with second solution answer from MSDN forum post How to find the weekend days in sql server 2008. The idea is simple: we create common table expression (CTE) for given year dates and select out only those where name of week day is Saturday or Sunday.
But what about calendar table? Customer has in database some sort of lightweight calendar table but this is only for holidays and I can use it to find out shorter working days before national holidays. Those who start with green-field project can also consider using calendar tables like shown in aricle Date and Time – Create Master Calendar Table.
Getting weekend days in month
First I modified the answer to get back weekend days in given month.
DECLARE @Date date SET @Date = CONVERT(DATE, '2017-03-01') ;WITH CTE AS ( SELECT @Date AS [Date], MONTH(@Date) As [Month], DATENAME (MONTH,@Date) AS [MonthName], DATENAME (DW,@Date) AS [DayName] UNION ALL SELECT DATEADD(DAY,1,[DATE]) AS [Date], MONTH(DATEADD(DAY,1,[DATE])) AS [Month], DATENAME (MONTH,DATEADD(DAY,1,[DATE])) AS [MonthName], DATENAME (DW ,DATEADD(DAY,1,[DATE])) AS [DayName] FROM CTE WHERE YEAR(DATEADD(DAY,1,[DATE]) )=YEAR(@Date) AND MONTH(DATEADD(DAY,1,[DATE]))=MONTH(@Date) ) SELECT * FROM CTE WHERE [DayName] IN ('Saturday','Sunday') ORDER BY [DATE] OPTION (MAXRECURSION 367)
Running this SQL script in SSMS gives the following output.
If needed it’s possible to add more fields or remove existing ones based on current needs.
I left all fields from my first code to visualize better what is returned by CTE.
Getting count of weekend days in month
I used previous script to write function that return count of weekend days in given month.
CREATE FUNCTION GetWeekendDaysCount ( @Date datetime ) RETURNS int AS BEGIN DECLARE @WeekendDays int ;WITH CTE AS ( SELECT @Date AS [Date], MONTH(@Date) As [Month], DATENAME (MONTH,@Date) AS [MonthName], DATENAME (DW,@Date) AS [DayName] UNION ALL SELECT DATEADD(DAY,1,[DATE]) AS [Date], MONTH(DATEADD(DAY,1,[DATE])) AS [Month], DATENAME (MONTH,DATEADD(DAY,1,[DATE])) AS [MonthName], DATENAME (DW ,DATEADD(DAY,1,[DATE])) AS [DayName] FROM CTE WHERE YEAR(DATEADD(DAY,1,[DATE]) )=YEAR(@Date) AND MONTH(DATEADD(DAY,1,[DATE]))=MONTH(@Date) ) SELECT @WeekendDays = COUNT(*) FROM CTE WHERE [DayName] IN ('Saturday','Sunday') OPTION (MAXRECURSION 367) RETURN @WeekendDays END
Notice that for count there is no need for ORDER BY. To try out the function we can use the following SQL script.
DECLARE @Date date SET @Date = CONVERT(DATE, '2017-03-01') SELECT dbo.GetWeekendDaysCount(@Date)
It returns correctly 8 as a result. I can use the same call also in my tored procedure that returns data for report.
Wrapping up
Although it is usually good idea to use calendar tables that we can fill automatically it is not always an option. It is also possible it is overkill for given solution. Using CTE-s to find weekend days in given month is actually easy although the code doesn’t look simple for SQL beginners or application developers like me. Still I consider this solution good one as finding weekend days happens in database and there’s no need for WHILE loops and cursors. The code given here is easy to modify to meet other needs related to days of given month.
View Comments (7)
I'd usually recommend a DATEPART comparison, using "known good" dates, rather than relying on specific language settings or DATEFIRST settings. E.g. rather than
[DayName] IN ('Saturday','Sunday')
I'd prefer something along the lines of
DATEPART(weekday,[Date]) IN (DATEPART(weekday,'20150905'),DATEPART(weekday,'20150906')) --Saturdays, Sundays
Because then the script works for everyone, rather than being English/US centric. It performs about the same
Thanks for advice, Damien. Going with "guaranteed" days is excellent solution.
Hiya, I am really glad I have found this info. Today bloggers publish just about gossips and net and this is actually frustrating. A good website with interesting content, this is what I need. Thanks for keeping this site, I will be visiting it. Do you do newsletters? Can't find it.
Yet another thing is that when evaluating a good on the internet electronics retail outlet, look for web shops that are consistently updated, keeping up-to-date with the latest products, the best deals, and helpful information on goods and services. This will ensure that you are handling a shop that really stays ahead of the competition and provides you what you should need to make knowledgeable, well-informed electronics buying. Thanks for the vital tips I have learned from the blog.
Nearly all of the things you mention is supprisingly precise and that makes me ponder the reason why I had not looked at this in this light before. This article really did turn the light on for me as far as this subject goes. Nevertheless at this time there is one particular position I am not really too comfy with and whilst I make an effort to reconcile that with the actual main theme of the issue, allow me see exactly what the rest of your readers have to point out.Nicely done.
Valuable information. Lucky me I found your web site by accident, and I'm shocked why this accident didn't happened earlier! I bookmarked it.
I really like what you guys are up too. Such clever work and exposure! Keep up the wonderful works guys I've added you guys to our blogroll.