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.
Note
Enter the DOB here in the YYYY-MM-DD format. Then, run the complete code and you will get the output like below.
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.
- /** SQL SCRIPT for Age Calculation based on DOB given below in Years , Months , Days ***/
- Declare @Today date,@dob date, @TodayN int,@dobN int, @daysBM int, @years int, @months int, @days int
-
- set @Today = GETUTCDATE() /*** Today's Date for Calculation : Please Don't change this **/
- set @dob = '2012-02-29' /** Enter Date_Of_Birth here in YYYY-MM-DD Format **/
-
- set @TodayN = convert(nvarchar(10),@Today,112)
- set @dobN = convert(Nvarchar(10),@dob,112)
- set @years = ( @TodayN - @dobN)/10000
- set @months =(1200 + (month(@Today)- month(@dob))*100 + day(@Today) - day(@dob))/100 %12
- set @daysBM = day(dateadd(d,-1,left(convert(Nvarchar(10),dateadd(M,1,@dob),112),6)+'01'))
- 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))
-
- Select @years as [Yrs],@months [Months],@days [Days]