DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Why Database Migrations Take Months and How to Speed Them Up
  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • How Trustworthy Is Big Data?

Trending

  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 1
  • A Complete Guide to Modern AI Developer Tools
  • Building Resilient Networks: Limiting the Risk and Scope of Cyber Attacks
  1. DZone
  2. Data Engineering
  3. Databases
  4. MSSQL: Finding Weekend Days in Month

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.

By 
Gunnar Peipman user avatar
Gunnar Peipman
·
Jun. 05, 17 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
13.6K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Database

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

Opinions expressed by DZone contributors are their own.

Related

  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Why Database Migrations Take Months and How to Speed Them Up
  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • How Trustworthy Is Big Data?

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: