Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2008

Find All the Days Between Two Dates

4.64/5 (5 votes)
19 Aug 2013CPOL 46.4K  
Find all the days between two dates using SQL Server

Introduction

Sometimes, a business requires all days with date between two dates. There are many ways to get this done, but I am introducing a very simple way to do this using SQL Server.

Using the Code

SQL
Create PROCEDURE getAllDaysBetweenTwoDate
(
@FromDate DATETIME,    
@ToDate DATETIME
)
AS
BEGIN
    
    DECLARE @TOTALCount INT
    SET @FromDate = DATEADD(DAY,-1,@FromDate)
    Select  @TOTALCount= DATEDIFF(DD,@FromDate,@ToDate);

    WITH d AS 
            (
              SELECT top (@TOTALCount) AllDays = DATEADD(DAY, ROW_NUMBER() 
                OVER (ORDER BY object_id), REPLACE(@FromDate,'-',''))
              FROM sys.all_objects
            )
        SELECT AllDays From d
        
    RETURN 
END
GO

--Exec getAllDaysBetweenTwoDate '12-31-2013','01-05-2014' 
--Date Formate will be 'MM-dd-yyyy'

639460/Untitled.jpg

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)