User-defined function to calculate age at specified date

Aidan Devlin 21 Reputation points
2022-12-01T09:03:10.19+00:00

Hi, I need a user-defined function in SQL that will calculate the age of someone at a provided date. The user input to the function should be a person's ID number and a specified date. The date of birth is confidential and so cannot be used or seen by the user.

I have the calculation for Age, which I will post below, I am just unsure of how to create the function due to the sensitivity and confidentiality of the date of birth.

Thanks,
Aidan

CASE
WHEN dateadd(year, datediff (year, i.DATE_OF_BIRTH, getdate()), i.DATE_OF_BIRTH) > getdate()
THEN datediff(year, i.DATE_OF_BIRTH, getdate()) - 1
ELSE datediff(year, i.DATE_OF_BIRTH, getdate())
END AS CURRENT_AGE

SSMS v18.2

Developer technologies | Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-12-01T09:17:28.953+00:00

    Maybe define it like this:

    create function GetAge( @PersonID int )  
    returns int   
    as  
    begin  
        declare @age int  
      
        select @age =   
            CASE  
            WHEN dateadd(year, datediff (year, i.DATE_OF_BIRTH, getdate()), i.DATE_OF_BIRTH) > getdate()  
            THEN datediff(year, i.DATE_OF_BIRTH, getdate()) - 1  
            ELSE datediff(year, i.DATE_OF_BIRTH, getdate())  
            END   
        from Person i  
        where PersonID = @PersonID  
      
        return @age  
    end  
    

    It returns the age, but does not reveal the date of birth.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.