I have table with the week_date
stored as nvarchar(60)
. When I tried to change that to date
, I'm getting below error.
Records in the table are in yyyy-mm-dd
format
WEEK_DATE
----------
2017-12-31
2018-01-01
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
I have used the below to convert, but that throws an error
SET WEEK_DATE = CONVERT(NVARCHAR(260), WEEK_DATE, 120)
Thank you
Use try_convert()
to find the bad values:
select datecol
from t
where try_convert(date, datecol) is null and datecol is not null;
You can use try_convert()
in your code, but you should investigate the data problem.
EDIT:
To change the column to a date, first verify the format (so you don't get an error with the conversion):
update t
set week_date = try_convert(date, week_date);
Don't worry about the format. It will use whatever the localization settings are. But happily, the resulting string will automatically be converted back to a date.
Then, alter the table:
alter table t
alter week_date date;
You might want to use the first query to check that all dates strings are actually recognized.
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.