-1

Possible Duplicate:
Getting week number off a date in MS SQL Server 2005?

Please suppose (i am in Italy) that all the weeks start with Monday and end with Sunday.

I would like to write a scalar valued function that determines the number of the week with reference to GETDATE()

Thank you in advance for your kind cooperation.

PLEASE PAY ATTENTION TO THIS: The SELECT has to be INDIPENDENT from the SET DATEFIRST command!!

Community
  • 1
  • 1
UltraCommit
  • 2,236
  • 7
  • 43
  • 61

4 Answers4

3

Can you use the two liner?

  SET DATEFIRST 1;
  SELECT DATEPART( WEEK , GETDATE())

for today

SELECT DATEPART( WEEK , GETDATE())

returns 30 whereas

SET DATEFIRST 1;
SELECT DATEPART( WEEK , GETDATE()) 

returns 31

Edit Untested but based on This Question you can get the equivalent of the SQL Server 2008 datepart(iso_week, getdate()) (which i believe is what you want) with the following select statement

SELECT ISOWeek = (DATEPART(DY, Th) - 1) / 7 + 1
FROM (SELECT Th = DATEADD(D, 3 - (DATEPART(DW, getdate()) + @@DATEFIRST - 2) % 7, getdate())) s
Community
  • 1
  • 1
Manatherin
  • 4,169
  • 5
  • 36
  • 52
1

Here's a little snippet that should do what you need.

DECLARE @firstOfYear DATETIME
SET @firstOfYear = STR(Year(GETDATE()), 4)+'-01-01 00:00:00'
SELECT DATEDIFF(ww, @firstOfYear - ((DATEPART(dw, @firstOfYear) + 5) % 7), GETDATE())

Keep in mind that if you want to set the week start to on a different day, just change the +5 to the value based on 7 - dw. This is for MSSQL.

This works by getting the first day of the year and finding the day of the starting week on or before that day. Then we get the number of weeks between whatever date was passed in and that "first" week start. If you want to allow any date to be passed in, just replace all GETDATE calls with your parameter and you should be good to go. If you need a single select statement:

SELECT 
    DATEDIFF(ww, day1 - ((DATEPART(dw, day1) +5) % 7), GETDATE()) 
FROM 
    (SELECT CAST(STR(Year(GETDATE()), 4)+'-01-01 00:00:00' AS DATETIME) day1) d
SPFiredrake
  • 3,852
  • 18
  • 26
0
select datepart(week,getdate())

more at http://msdn.microsoft.com/en-us/library/aa258265(v=sql.80).aspx

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
0
declare @oldDF int
set @oldDF = @@DATEFIRST

set DATEFIRST 1
select DATEPART(WEEK, GETDATE())

set DATEFIRST @oldDF
Dan Pichelman
  • 2,312
  • 2
  • 31
  • 42