Click here to Skip to main content
15,890,845 members
Articles / Database Development / SQL Server / SQL Server 2008
Tip/Trick

Find All the Days Between Two Dates

Rate me:
Please Sign up or sign in to vote.
4.64/5 (5 votes)
19 Aug 2013CPOL 45.8K   6   5
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)


Written By
Software Developer (Senior)
India India
Play with programming languages and Technologies....
(C#,C++,JAVA,PYTHON,PL/SQL,T-SQL,Shell Scripting,SQL)

Comments and Discussions

 
QuestionDoubt Pin
Member 1152885616-Mar-15 1:55
Member 1152885616-Mar-15 1:55 
GeneralMy vote of 3 Pin
coded00720-Aug-13 22:39
professionalcoded00720-Aug-13 22:39 
Looks good
QuestionAnother way to do it :) Pin
ZGZike20-Aug-13 19:50
ZGZike20-Aug-13 19:50 
GeneralRe: Another way to do it :) Pin
S.P.Tiwari20-Aug-13 20:08
professionalS.P.Tiwari20-Aug-13 20:08 
SuggestionRe: Another way to do it :) Pin
S.P.Tiwari20-Aug-13 20:35
professionalS.P.Tiwari20-Aug-13 20:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.