将 varchar 转换为 Datetime
为什么以下代码有效:
CAST(DateOfAction AS Date)
但此代码无效:
CAST(DateOfAction AS Datetime)
注意:DateOfAction
是一个 varchar
字段
有人可以解释一下并给出正确的代码吗?
Why does the following code work:
CAST(DateOfAction AS Date)
but this code does not:
CAST(DateOfAction AS Datetime)
note: DateOfAction
is a varchar
field
Can someone explain this and give the right code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能是因为您的
VARCHAR
字段包含一个可能会转换为DATE
的值(无时间值),但不是 SQL Server CAST 和 SQL Server 所支持的任何有效格式。转换支持。由于您没有提供任何数据示例,我们只能猜测......
请查看 SQL Server 联机丛书 CAST 和 CONVERT 适用于将转换为
DATETIME
的所有受支持的有效格式。Possibly because your
VARCHAR
field contains a value that might convert to aDATE
(no time values), but isn't in any of the valid supported formats that SQL Server CAST and CONVERT support.Since you didn't provide any samples of what your data looks like, we can only guess.....
Check the SQL Server Books Online on CAST and CONVERT for all supported, valid formats that will convert to
DATETIME
.对于导致日期时间问题的某些值,日期具有“固定”行为。
例如,即使 ISO yyyy-mm-dd 也不是语言安全的
请参阅 Tibor Karaszi 的这篇文章。以及这个问题(在评论中)
Date has "fixed" behaviour for some values that caused issues with datetime.
For example yyyy-mm-dd is not language safe even though ISO
See this article by Tibor Karaszi. And this SO question (in the comments)
进行编辑
根据您正在使用的附加信息
yyyymmdd
格式我只能认为问题出在数据上。你可以尝试以下方法吗?
每个值都是您认为的格式吗?
datetime
是否可以接受该范围内的每个值?Edit
Following the additional information that you are using
yyyymmdd
format I can only think the problem is in the data.Can you try the following?
Is every value in the format you think it is?
Is every value in the range acceptable to
datetime
?除了指出日期具有某些不安全的转换(不适用于日期时间)的其他答案之外,还有一个事实是 日期范围大于日期时间。因此,如果您的日期早于 1753 年,则无论进行多少格式化/转换都不起作用。
另外,如果这不是为了将代码转换为在旧服务器上工作,而只是为了获得时间组件,那么如果您的服务器上有可用的
date
,您应该有datetime2
,这样效果会好很多。Besides the other answers pointing out that date has certain conversions that are safe that aren't for datetime, there's also the fact that the range of date is larger than that for datetime. So if you have dates earlier than 1753, no amount of formatting/conversion will work.
Also, if this isn't for converting code to work on an older server, but just to gain a time component, then if you've got
date
available on your server, you should havedatetime2
, which will work a lot better.