简体   繁体   English

SQL 服务器 2017 将 Varchar 转换为日期

[英]SQL Server 2017 Convert Varchar to Date

I have a date stored as nvarchar which I cannot seem to convert to a date.我有一个存储为nvarchar的日期,我似乎无法将其转换为日期。

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() :使用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.或者只是使用try_convert()来获取NULL以获得不可转换的值。

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

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