65.9K
CodeProject is changing. Read more.
Home

Find Week in Given Date in SQL Server

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.38/5 (6 votes)

Feb 5, 2007

CPOL
viewsIcon

52111

This sql function is used to find the week in Given Date.

Introduction

This small article is explained, How to find a week in given date from sql server. In Many scanerio we need to prepare the records in weekly basis. In this case, the below funciton is very useful to find the week in given date.

Create Function dbo.FindInWeek (@givendate datetime)
returns varchar(15)
as
begin
declare @firstDayOfMonth varchar(20),
@findWeek int,@weeks varchar(30)
set @firstDayOfMonth = cast(month(@givenDate) as varchar(2))+'/'+'1'
+'/'+ cast(year(@givenDate) as varchar(4))
set @findWeek= datepart(wk, @givendate) - datepart(wk, @firstDayOfMonth) + 1
set @weeks=case @findWeek
when 1 then 'First'
when 2 then 'Second'
when 3 then 'Third'
when 4 then 'Fourth'
when 5 then 'Fifth'
when 6 then 'Sixth'
else 'Seventh' end
return @weeks+' Week'
end

How to call this function from Sql sever?

select dbo.FindInWeek('02/05/2007')

Output

Second Week