Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
Hi friends,

I have to insert YEAR WEEKNUMBER STARTDATE ENDDATE values to a datatable( say weekrange). If I pass 2011 as year

WEEK RANGE STARTS FROM '2011-03-28 ' TO '2011-04-03'.(Because in my database 2010 last week range endds with '2011-03-27')

Like this I have to generate for 52 weeks.

I want to write a stored procedure, that takes only year as parameter. with this year I have to generate week ranges and insert into my table as shown above.

how can I do this ?

Regards,

jn
Posted

You can use DATEPART to determine what week the current date is. Below is a code that demonstrates it.

SQL
DECLARE @currentDayOfWeek AS INT
DECLARE @currentDate AS DATETIME
DECLARE @startDate AS DATETIME
SET @currentDayOfWeek = (DATEPART(dw, GETDATE()) - 1) * -1
SET @currentDate = CAST(CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '/'
+ CAST(DAY(GETDATE()) AS VARCHAR(2)) + '/'
+CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS DATETIME)
SET @startDate = DATEADD(DW,@currentDayOfWeek,@currentDate)
SELECT YEAR(@currentDate) AS [YEAR],
DATEPART(WW, @currentDate) AS WEEK,
@startDate AS STARTDATE,
DATEADD(DW, 6, @startDate) AS ENDDATE


Output is

SQL
YEAR   WEEK   STARTDATE   ENDDATE
2011   13     03/20/2011  03/26/2011

Note that you week is 13 because it computes for the week number for the whole year. You need to do a little subtraction if you want it to do the week numbers by month and not by year.

Not an elegant solution but it can give you a headstart on what you need to do. :)
 
Share this answer
 
Comments
Dalek Dave 23-Mar-11 10:47am    
Good Answer.
here is the link
sriramjithendra.blogspot.com
 
Share this answer
 
v2
Comments
Dalek Dave 23-Mar-11 10:47am    
Blowing your own trumpet? :)
but it works.

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