June 2008
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          
Search

 
Catagories
Archives
Recent Entries
Links
RSS
it's your birthday...
Catagory: sql server · This Entry · Comment(0) · eMail entry · Google
April 15, 2004 04:32 PM

sql server

here's a way to calculate someone's age on a given date. also, you can also sort by birthday (month/day) excluding the year.

the query just performs a datediff, BUT adjusts by 0/1 given the time of year -- before or after the person's birthday.

i.e. you just need to adjust by "-1" if the date you're evaluating is prior to the birthday in that year.


calculate age :

DECLARE @DOB datetime, @later datetime
SELECT @DOB='07/1/1970', @later='07/1/2003'

Select DateDIFF( yy, @DOB, @later ) -
CASE
WHEN @later >= DateAdd( yy, DateDIFF(yy,@DOB,@later), @DOB )
THEN 0
ELSE 1
END
AS Age

here's the 'birthday' sort :

select * from customers
order by Datepart(mm, @dob), Datepart(dd, @dob)



here's another example, though not as slick as the one above, for calculating age (works on the same principle).

select datediff( yy, @dob, @later ) -
case
when 100*month(@dob) + day(@dob) >= 100*month(@later) + day(@later)
then 0
else 1
end as age





Comments

Post a comment
Name:


Email Address:


URL:


Comments: