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

Whether you work in SQL Server Management Studio or Visual Studio, Redgate tools integrate with your existing infrastructure, enabling you to align DevOps for your applications with DevOps for your SQL Server databases. Discover true Database DevOps, brought to you in partnership with Redgate.

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.

It’s easier than you think to extend DevOps practices to SQL Server with Redgate tools. Discover how to introduce true Database DevOps, brought to you in partnership with Redgate

Topics:
database ,mssql ,tutorial ,calendar tables

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}