Houari
Houari

Reputation: 5631

function calculate the right week number of year

I am looking for function that give me the right week-number.

The first day of the year should always be on week number 1. The first saturday of a year belongs to the first week.

In another words: here is what i am looking for, but not in PostgreSQL, but in sql-server.

I realy want to do that using a function that i will call later.

Thank you in advance for your help.

Upvotes: 1

Views: 194

Answers (2)

djangojazz
djangojazz

Reputation: 13242

select datepart(week, getdate()) as CurrentWeekofYear

Upvotes: 0

Cristian Lupascu
Cristian Lupascu

Reputation: 40526

In SQL Server there's no need for a custom function; just use the built in DATEPART function with week as the first argument:

-- first day
select datepart(week, '2013-01-01');

Output: 1

-- first Saturday
select datepart(week, '2013-01-05');

Output: 1

-- first Sunday
select datepart(week, '2013-01-06');

Output: 2

-- today
select datepart(week, '2013-04-01');

Output: 14

Here's a live demo: http://www.sqlfiddle.com/#!3/d41d8/11802

Upvotes: 1

Related Questions