Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get each day number of a month in SQL?

Is there a way to get a select with each day number of a month? For example I have this date: 2021-12-15 and I want to get this result:

| Days| 
|--------| 
|  1|
|  2|
|  3|
|  4|
|  5|

.. 31

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a simple recursive CTE to generate a list of numbers and eomonth() for the days in the given date:

declare @date date='20211215';

with d as (
    select 1 num
    union all
    select d.num + 1
    from d
    where d.num <= 31
)
select num as [Days]
from d
where num<=Day(EOMonth(@date));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading