SQL Query To Calculate Age Using Given Date Of Birth (DOB)

Calculating Age from the given Date of Birth (DOB )

 
It is very simple to calculate the age in many cases we come across, using the SQL query. Please follow the below instructions where you will get the age from the given date of birth.
 
Enter your date of birth in the code line mentioned (red color). For example, if your date of birth is 2012-02-29, then enter it in the input parameter @dob.
  1. set @dob = '2012-02-29' ---- This is your input parameter  
Note
 
Enter the DOB here in the YYYY-MM-DD format. Then, run the complete code and you will get the output like below.
 
SQL Query to Calculate Age using given Date of birth (DOB)
The following is the SQL code as mentioned above to get the age from the given DOB. Run the complete
code for given date of birth and you will get the age derived in years, months, and days, as shown in the image below.
  1. /** SQL SCRIPT for Age Calculation based on DOB given below in Years , Months , Days ***/  
  2. Declare @Today date,@dob date, @TodayN int,@dobN int, @daysBM int, @years int, @months int, @days int  
  3. ----- Inputs ------  
  4. set @Today = GETUTCDATE() /*** Today's Date for Calculation : Please Don't change this **/  
  5. set @dob = '2012-02-29' /** Enter Date_Of_Birth here in YYYY-MM-DD Format **/  
  6. -- Calculcation Part ---  
  7. set @TodayN = convert(nvarchar(10),@Today,112)  
  8. set @dobN = convert(Nvarchar(10),@dob,112)  
  9. set @years = ( @TodayN - @dobN)/10000  
  10. set @months =(1200 + (month(@Today)- month(@dob))*100 + day(@Today) - day(@dob))/100 %12  
  11. set @daysBM = day(dateadd(d,-1,left(convert(Nvarchar(10),dateadd(M,1,@dob),112),6)+'01'))  
  12. set @days = (sign(day(@Today) - day(@dob))+1)/2 * (day(@Today) - day(@dob))+ (sign(day(@dob) - day(@Today))+1)/2 * (@daysBM - day(@dob) + day(@Today))  
  13. --- Final Result of the Query ---  
  14. Select @years as [Yrs],@months [Months],@days [Days]