简体   繁体   中英

SQL Server 2017 Convert Varchar to Date

I have a date stored as nvarchar which I cannot seem to convert to a date.

I have tried the following but get the error message

Conversion failed when converting date and/or time from character string

select cast([month-year] as date) from [Reporting].[AIM].[Hires_PBI]

select convert(date, [month-year], 103)from [Reporting].[AIM].[Hires_PBI]

Any ideas here?

Find the values that are causing the problem using try_convert() :

select [month-year] 
from [Reporting].[AIM].[Hires_PBI]
where try_convert(date, [month-year], 103) is null and
      [month-year] is not null;

Once you see what values are causing the problem, you can adjust the conversion logic to convert all values. Or just use try_convert() to get NULL for the non-convertible values.

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