简体   繁体   中英

SQL Server calculating age from varchar date of birth

The stored procedure is provided with @minAge and @maxAge varchar values.

The table contains DOB column as a varchar , now I need to select rows where where DOB (Age) falls between minimum and maximum age.

For instance @minAge = 12 and @maxAge = 40 , we have to first convert the DOB string into Current Age and then only select the rows which fall between (inclusive) of 12 and 40.

I have the following code in mind but that produces errors

SELECT * 
FROM tableName
WHERE
    FLOOR((CAST(GetDate() AS INTEGER) - CAST(DOB AS INTEGER)) / 365.25) AS Age
      BETWEEN CAST(@minage AS INT) AND CAST(@maxAge AS INT)

One way of calculating the age is this:

DATEDIFF(YY, CAST(dob AS DATETIME), GETDATE()) - CASE WHEN( (MONTH(CAST(dob AS DATETIME))*100 + DAY(CAST(dob AS DATETIME))) > (MONTH(GETDATE())*100 + DAY(GETDATE())) ) THEN 1 ELSE 0 END AS Age

where dob is the date of birth stored as varchar (in a way that can be cast to a datetime).

An example:

declare @people table(name varchar(20), dob varchar(10))
insert @people values ('adam', '1970-01-01')
insert @people values ('burt', '2002-01-13')
insert @people values ('dave', '1992-11-13')
insert @people values ('eric', '1973-11-13')

SELECT 
    name, 
    DATEDIFF(YY, CAST(dob AS DATETIME), GETDATE()) - CASE WHEN( (MONTH(dob)*100 + DAY(dob)) > (MONTH(GETDATE())*100 + DAY(GETDATE())) ) THEN 1 ELSE 0 END AS Age
FROM @people 
WHERE DATEDIFF(YY, dob, GETDATE()) - CASE WHEN( (MONTH(dob)*100 + DAY(dob)) > (MONTH(GETDATE())*100 + DAY(GETDATE())) ) THEN 1 ELSE 0 END
BETWEEN 12 AND 40

This would be the result:

name    Age
burt    12
dave    21
eric    40

This might not be the best way though, but it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM