Calculate Age Function in T-SQL


Create function dbo.FunAgeCalc(@DOB datetime)

returns smallint

as

begin

return (

select case when month(@DOB)>month(getdate()) then datediff(yyyy,@DOB,getdate())-1

when month(@DOB)<month(getdate()) then datediff(yyyy,@DOB,getdate())

when month(@DOB)=month(getdate()) then

case when day(@DOB)>day(getdate())

then datediff(yyyy,@DOB,getdate())-1

else datediff(yyyy,@DOB,getdate())

end

end

)

end

to use it:

select dbo.FunAgeCalc(CAST(‘2000-05-05 08:00:00.000’ As DateTime)) as Age

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s