Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Create DateTime based off Year and Week Number

Author  Topic 

JustinCarmony
Starting Member

2 Posts

Posted - 2008-01-11 : 12:04:33
Is there a way I can create a user defined function that takes a year int and week number int and return the datetime value of the first day of that week?

Example:

I set my FIRSTDATE to 1 (for monday) and I pass my function 2008 for the year and week 2 for my week. I want it to return a datetime value for the date '2008-01-07' because its the starting date of the second week of the year? I hope my question has been clear enough and thanks for any help!

Justin

jdaman
Constraint Violating Yak Guru

354 Posts

Posted - 2008-01-11 : 12:11:44
select dateadd(week, @week, dateadd(year, @year - 1900, 0))-2
Go to Top of Page

JustinCarmony
Starting Member

2 Posts

Posted - 2008-01-11 : 12:12:54
k, I understand everything in that query except for the -2 at the end. What is that for?

Justin

**edit** also, thank you for the fast reply :)
Go to Top of Page

jdaman
Constraint Violating Yak Guru

354 Posts

Posted - 2008-01-11 : 12:22:29
Thats what you get when you write sloppy quick code...:/

Try this:
select dateadd(week, @week, dateadd(year, @year - 1900, 0))-datepart(w, dateadd(week, @week, dateadd(year, @year - 1900, 0)))-5
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2008-01-11 : 12:26:28
[code]
select TOP 1
a.[Date]
from
-- Date Table Function F_TABLE_DATE available on following link:
-- http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=61519
F_TABLE_DATE('20080101','20081231') a
where
ISO_WEEK_NO = 2


Results:
Date
------------------------------------------------------
2008-01-07 00:00:00.000

(1 row(s) affected)
[/code]

CODO ERGO SUM
Go to Top of Page
   

- Advertisement -