Skip to main content

This T-SQL function is used to calculate the age from the given date.

-- Calculate Age
--
-- This function is used to calculate the age from the given date.
--

create function [dbo].[fn_calc_age]
(
    @dob datetime
)
returns varchar(64)
as
begin
    declare @age int
    declare @getdate datetime = getdate()

    if @dob >= @getdate
        return 'Invalid Input'

    set @age = datediff(yy, @dob, @getdate)

    if month(@dob) > month(@getdate) or
      (month(@dob) = month(@getdate) and
       day(@dob)   > day(@getdate))
        set @age = @age - 1

    return convert(varchar, @age) + ' Years and ' + convert(varchar, datediff(dd, dateadd(yy, @age, @dob), @getdate)) + ' Days'
end;

go