简体   繁体   English

使用代表年、月和日的 3 列计算年龄

[英]Calculate age using 3 columns representing year, month and date

I have 3 columns dob_year, dob_month, dob_day, all 3 columns are data type nvarchar(50).我有 3 列 dob_year、dob_month、dob_day,所有 3 列都是数据类型 nvarchar(50)。 when I try to calculate age comparing dob (date of birth) with gatedate() I will get message "Conversion failed when converting date and/or time from character string.".当我尝试用 gatedate() 计算年龄比较 dob(出生日期)时,我会收到消息“从字符串转换日期和/或时间时转换失败。”。

DATEDIFF(yy, (s.dob_year+'-'+s.dob_month+'-'+s.dob_day), GETDATE())as age, 

I tried to use same function together with convert() or cast() functions I will get same message.我尝试将相同的 function 与 convert() 或 cast() 函数一起使用,我会得到相同的消息。

Your syntax suggests that you are using SQL Server.您的语法表明您正在使用 SQL 服务器。 If your values are all ok, you can use:如果您的值都可以,您可以使用:

datefromparts(s.dob_year, s.dob_month, s.dob_day)

However, if you have bad combinations (such as Feb 31st), then you need a TRY_ function.但是,如果您有错误的组合(例如 2 月 31 日),那么您需要一个TRY_ For that, I would suggest:为此,我建议:

try_convert(date, convert(varchar(8), s.dob_year * 10000 + s.dob_year * 100 + s.dob_day))

This puts the three columns in the format YYYYMMDD, which can then be converted readily to a date.这会将三列的格式设置为 YYYYMMDD,然后可以轻松地将其转换为日期。

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

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