Monday, September 12, 2005

TSQL date teaser. Answer for Q2

2) Given a date, find the date of the first day and last day of the month.
E.G: Given 21-July-2005, You have to tell 1-July-2005 is the first day of
the month and 31-July-2005 is the last day of the month.


declare @startOfNextMonth datetime
declare @endOfMonth datetime
declare @myDate varchar(20)

select @myDate = '21-feb-2005'

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

select @startOfNextMonth = dateadd(m, 1, @startOfMonth)
print @startOfNextMonth

select @endOfMonth = dateadd(d, -1 , @startOfNextMonth)
print @endOfMonth

Labels:

0 Comments:

Post a Comment

<< Home