Question:

Using a sql query how to calculate age from DOB

by  |  earlier

0 LIKES UnLike

for displayin records of persons whose age is greater than 18.

select *from table where ( (CURDATE()-dob) > 18)

is it correct...?

ll it work..?

 Tags:

   Report

2 ANSWERS


  1. Rengas solution is very good, so I don't want to second guess ... however your additional details say you want it in a single query.

    select * from table where addyears(dob, 18) > curdate()


  2. build a user-defined function (UDF) in SQL Server and call it from the Stored Procedure

    Create FUNCTION dbo.GetAge (@DOB datetime, @Today Datetime) RETURNS Int

    AS

    Begin

    Declare @Age As Int

    Set @Age = Year(@Today) - Year(@DOB)

    If Month(@Today) < Month(@DOB)

    Set @Age = @Age -1

    If Month(@Today) = Month(@DOB) and Day(@Today) < Day(@DOB)

    Set @Age = @Age - 1

    Return @AGE

    End

    SELECT *

    FROM Table

    WHERE  dbo.GetAge(e.Date_Of_Birth, getdate()) >= 18

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.