简体   繁体   English

SQL Server从varchar出生日期开始计算年龄

[英]SQL Server calculating age from varchar date of birth

The stored procedure is provided with @minAge and @maxAge varchar values. 该存储过程具有@minAge@maxAge varchar值。

The table contains DOB column as a varchar , now I need to select rows where where DOB (Age) falls between minimum and maximum age. 该表包含DOB列作为varchar ,现在我需要选择DOB (年龄)介于最小年龄和最大年龄之间的行。

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. 例如, @minAge = 12@maxAge = 40 ,我们必须首先将DOB字符串转换为Current Age,然后才选择介于(包括)12和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). 其中dob是存储为varchar的出生日期(可以转换为日期时间)。

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. 虽然这可能不是最好的方法,但是应该可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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