Click here to Skip to main content
15,906,463 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want week dates between specified date range inclusive date range in SQL. Like

If, @Start = '2014-05-01 00:00:00.000' and @End = '2014-05-31 00:00:00.000' Dates are this

CSS
1   2014-05-01 00:00:00.000 2014-05-07 00:00:00.000
2   2014-05-07 00:00:00.000 2014-05-14 00:00:00.000
3   2014-05-14 00:00:00.000 2014-05-21 00:00:00.000
4   2014-05-21 00:00:00.000 2014-05-28 00:00:00.000
5   2014-05-28 00:00:00.000 2014-05-31 00:00:00.000



If, @Start = '2014-05-01 00:00:00.000' and @End = '2014-05-1800:00:00.000' Dates are this

CSS
1   2014-05-01 00:00:00.000 2014-05-07 00:00:00.000
2   2014-05-07 00:00:00.000 2014-05-14 00:00:00.000
3   2014-05-14 00:00:00.000 2014-05-18 00:00:00.000


Thanks in Advance
Posted
Updated 11-Jun-14 2:01am
v2

1 solution

try this.. :)

SQL
declare @fromDate datetime,@toDate datetime
set @fromDate='12 Jun 2014'
set @toDate='28 Jun 2014'


 ;WITH CTEQuery AS (
			  SELECT CAST(@fromDate AS DATETIME) AS FirstDay, DATEADD(dd, 7, @fromDate) as LastDay
			  UNION ALL
			  SELECT DATEADD(dd, 7, FirstDay), DATEADD(dd, 7, LastDay)
			   FROM CTEQuery s
			   WHERE DATEADD(dd, 7, FirstDay) <= CAST(@toDate AS DATETIME)
			   )
select * from CTEQuery 


you can pass @fromDate and @toDate dynamically here i have passed it for example.. :)
 
Share this answer
 
v3
Comments
chetna2810 11-Jun-14 7:01am    
Sir,
It is showing dates of may month in result. I want record starting from @fromDate and ending on @toDate.
Actually i want to extract records from the table week wise thats y dates should be specific.
Nirav Prabtani 11-Jun-14 7:04am    
ok wait i'll looj into it.
chetna2810 11-Jun-14 7:07am    
thnx Sir..
Nirav Prabtani 11-Jun-14 7:10am    
see updated solution if it doesn't work then tell me i'll give better.. :)
chetna2810 11-Jun-14 7:18am    
Sir,
Your solution left dates come before @fromDate and after @toDate.
Presntly it is showing
2014-06-15 00:00:00.000 2014-06-21 00:00:00.000

But i want
2014-06-12 00:00:00.000 2014-06-18 00:00:00.000
2014-06-19 00:00:00.000 2014-06-25 00:00:00.000
2014-06-25 00:00:00.000 2014-06-26 00:00:00.000

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900