Thursday, September 15, 2005

TSQL date teaser. Answer for Q5

5). Given a date, find the first Tuesday of the month.
E.G: Given 10-July-2005, first Tuesday for the month is 5-July-2005.


declare @startOfNextMonth datetime
declare @endOfMonth datetime
declare @myDate varchar(20)
declare @DaysToAdd int
declare @TargetDayOfWeek int

select @myDate = '10-jul-2005'
select @TargetDayOfWeek = 3

select @startOfMonth = dateadd(d, (day(@myDate)-1)* -1, @myDate)
print @startOfMonth

select @DaysToAdd = (7 - ((datepart(dw,@startOfMonth) +
(7 - @TargetDayOfWeek)) % 7)) % 7

select dateadd(d, @DaysToAdd, @startOfMonth)

Labels:

0 Comments:

Post a Comment

<< Home