Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MSSQL: Finding Weekend Days in Month

DZone's Guide to

MSSQL: Finding Weekend Days in Month

Although it is usually a good idea to use calendar tables that we can fill automatically, it is not always an option. Here's how to deal with that.

· Database Zone ·
Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

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 the calculation work is done in SQL Server stored procedures, 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 a given solution, it seemed the best idea to go with second solution answer from MSDN forum post on how to find the weekend days in SQL Server 2008. The idea is simple: we create common table expressions (CTE) for given year dates and select out only those where the name of week day is Saturday or Sunday.

But what about the calendar table? The customer has in the 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 the green-field project can also consider using calendar tables like shown in article .

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:

SQL Server: List of weekend days

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 the previous script to write a function that returns the 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 stored procedure that returns data for the report.

Wrapping Up

Although it is usually a good idea to use calendar tables that we can fill automatically, it is not always an option. It is also possible that it is overkill for your given solution. Using CTEs 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 a 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.

Get comfortable using NoSQL in a free, self-directed learning course provided by RavenDB. Learn to create fully-functional real-world programs on NoSQL Databases. Register today.

Topics:
database ,mssql ,tutorial ,calendar tables

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}