Finding the Number of Days of Months Within a Certain Date Range in SQL Server

Hello everybody,

In this article, I will try to give information about finding the number of days of the months within a certain date range in SQL Server.

In SQL Server, in some cases, you may want to find the number of days of the months within a certain date range.

You can easily do this using the code below.

DECLARE @baslamatarihi DATE = '2022-07-10';
DECLARE @bitistarihi DATE = '2022-09-10';
WITH sorgu
AS (SELECT DATEFROMPARTS(YEAR(@baslamatarihi), MONTH(@baslamatarihi), 1) ay_baslangic_gunu,
           1 - DAY(@baslamatarihi) + DAY(   CASE
                                                WHEN @bitistarihi > EOMONTH(@baslamatarihi) THEN
                                                    EOMONTH(@baslamatarihi)
                                                ELSE
                                                    @bitistarihi
                                            END
                                        ) AS gun_sayisi
    UNION ALL
    SELECT DATEADD(MONTH, 1, ay_baslangic_gunu),
           CASE
               WHEN @bitistarihi > DATEADD(MONTH, 2, ay_baslangic_gunu) THEN
                   DAY(EOMONTH(DATEADD(MONTH, 1, ay_baslangic_gunu)))
               ELSE
                   DAY(@bitistarihi)
           END
    FROM sorgu
    WHERE DATEADD(MONTH, 1, ay_baslangic_gunu) <= @bitistarihi)
SELECT *
FROM sorgu;

When you run the above code, you will see a result similar to the one below.

Finding the Number of Days of Months Within a Certain Date Range in SQL Server

As you can see, we have found the number of days of the months within a certain date range.

Good luck to everyone in business and life.

69 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!