Sunday, September 11, 2005

TSQL date teaser. Answer for Q1

This is a long outstanding post to my previous TSQL date teaser post.

1) Given a date, find the date of the first day and last day of that week.
E.G: Given 28-July-2005, You have to tell 24-July-2005 is the first day
of that week and 30-July-2005 is that last day of that week.

declare @dayOfWeek int
declare @startOfWeek datetime
declare @endOfWeek datetime
declare @myDate varchar(20)

select @myDate = '28-july-2005'
select @dayOfWeek = datepart(dw, @myDate)

select @startOfWeek = dateadd(d, (@dayOfWeek - 1)* -1, @myDate)
print @startOfWeek

select @endOfWeek = dateadd(d, 7 - @dayOfWeek , @myDate)
print @endOfWeek



Post a Comment

<< Home