Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

SQL query to return all dates between two date ranges for SQL Server 2005

Posted on 2008-10-18
13
Medium Priority
?
801 Views
Last Modified: 2012-05-05
There is a post ID: 23398111 which shows how to do this in Oracle but I need a solution for SQL Server,
See link @ http://www.experts-exchange.com/Database/Oracle/Q_23398111.html

The only solution I could come up with is be using an existing table that already contains rows see query below:
SELECT CONVERT(char(10),dateadd(day,ROW_NUMBER() OVER (order by ColD),getdate()), 112) CurrDate
FROM Tbl
0
Comment
Question by:HelmutP
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 2
13 Comments
 
LVL 39

Accepted Solution

by:
BrandonGalderisi earned 100 total points
ID: 22750307
The query would be:


declare @dtBegin datetime
     ,@dtEnd datetime
set @dtbegin = convert(datetime, '01/01/2008',101)
set @dtEnd = convert(datetime, '11/01/2008',101)

;with DateRange as
(
select @dtBegin theDAte
union all
select dateadd(d,n,@dtBegin) from vw_nums where n <= datediff(d,@dtBegin,@dtEnd)
)
select * from DateRange


and it uses the view below.
create view vw_Nums
as
with   cte0 as (select 1 as c union all select 1), 
       cte1 as (select 1 as c from cte0 a, cte0 b), 
       cte2 as (select 1 as c from cte1 a, cte1 b), 
       cte3 as (select 1 as c from cte2 a, cte2 b), 
       cte4 as (select 1 as c from cte3 a, cte3 b), 
       cte5 as (select 1 as c from cte4 a, cte4 b), 
       nums as (select row_number() over (order by c) as n from cte5)
       select n from nums 
 
 
go

Open in new window

0
 
LVL 11

Assisted Solution

by:Louis01
Louis01 earned 100 total points
ID: 22939142
This is a function I use for exactly that purpose:
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnCalendar]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnCalendar]
GO
 
CREATE FUNCTION [dbo].[fnCalendar](@StartDate [smalldatetime], @EndDate [smalldatetime])
RETURNS @retMonth TABLE (
	[CalDate] [smalldatetime] NULL
) WITH EXECUTE AS CALLER
AS 
BEGIN
    IF @StartDate IS NOT NULL
      AND @EndDate IS NOT NULL 
      BEGIN
		DECLARE @Duration int
		SET @Duration = (SELECT DATEDIFF(day, @StartDate, @EndDate))
        SET @StartDate = CONVERT(DATETIME, CONVERT(CHAR(10), DATEADD(d, (DATEPART(d, @StartDate) * -1) + 1, @StartDate), 120))
 
        DECLARE @Counter INTEGER
        SET @Counter = 0
        WHILE @Counter < @Duration
          BEGIN
            INSERT INTO
              @retmonth
            VALUES
              (
               DATEADD(DAY, @Counter, @StartDate))
            SET @Counter = @Counter + 1
          END
      END  
    RETURN
   END
GO
 
select * from dbo.fnCalendar('01-Jan-2007', '11-Nov-2008')

Open in new window

0
 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 23096127
I think that in the interest of "first come first serve" and considering I provided a solution almost a full month sooner, that I should get the full answer.
0
Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

 
LVL 11

Expert Comment

by:Louis01
ID: 23102537
I posted a different solution because the one proposed by BrandonGalderisi was still running 20 minutes after I tried it. (It subsequently gave an Exception of type 'System.OutOfMemoryException'). In the interest of not splitting hairs though, I am happy if BrandonGalderisi has the 50 points.
0
 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 23105006
20 minutes?
0
 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 23105078
The query I have posted above, which returns 306 records for Jan-1 to Nov-1 runs in 0 ms for me.  That means NO MEASURABLE TIME.

declare @dt datetime
set @dt=getdate()
declare @dtBegin datetime
     ,@dtEnd datetime
set @dtbegin = convert(datetime, '01/01/2006',101)
set @dtEnd = convert(datetime, '11/01/2008',101)
 
;with DateRange as
(
select @dtBegin theDAte
union all
select dateadd(d,n,@dtBegin) from vw_nums where n <= datediff(d,@dtBegin,@dtEnd)
)
select * from DateRange
 
select datediff(ms,@dt,getdate())

Open in new window

0
 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 23126027
cleanup?  as in delete?
0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 23129462
As in, 21 days from now I'm to make a recommendation again.
0
 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 24658054
I will re-state my earlier comment, but not object.


I think that in the interest of "first come first serve" and considering I provided a solution almost a full month sooner, that I should get the full answer.
0

Featured Post

Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question