I have 3 columns dob_year, dob_month, dob_day, all 3 columns are data type 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.".
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.
Your syntax suggests that you are using SQL Server. 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. 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.
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.