简体   繁体   English

为什么将日期从nvarchar(max)转换为日期会引发错误?

[英]Why converting date from nvarchar(max) to date throws error?

I have a date in this format 我有一个这样的日期

21-02-2018 

and using nvarchar(MAX) 并使用nvarchar(MAX)

I am trying to convert to date using 我正在尝试使用转换为日期

  select (Convert(Date, , 106)) from Certificates

  select (Convert(Date, IssueDate))

but it fails to convert. 但无法转换。

Use try_convert() . 使用try_convert() However, I think you want format 105 (dd-mm-yyyy), not 106 (dd mon yyyy): 但是,我认为您想要的格式为105(dd-mm-yyyy),而不是106(dd mon yyyy):

select try_convert(date, issuedate, 105)

This will return NULL instead of failing, when the format does not match. 当格式不匹配时,它将返回NULL而不是失败。 You can find these values: 您可以找到以下值:

select issuedate
from certificates
where try_convert(date, issuedate, 105) is null and
      issuedate is not null;

This is usually down to the format that the server is expecting the date to come in. I believe that it defaults to Month-Day-Year (American) rather than Day-Month-Year (British) 这通常取决于服务器预计日期的格式。我认为它默认为“月-日-年”(美国)而不是“日-月-年”(英国)。

Try putting SET DATEFORMAT DMY at the start of your code to hint that the first part of the string is Day not month. 尝试将SET DATEFORMAT DMY放在代码的开头,以提示字符串的第一部分是Day而不是month。

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

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