问题
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?
回答1:
Possibly because your VARCHAR
field contains a value that might convert to a DATE
(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
.
回答2:
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)
回答3:
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?
SELECT DateOfAction
FROM ResAdm.Action
WHERE DateOfAction NOT LIKE '[1-2][0-9][0-9][0-9][0-1][0-9][0-3][0-9]'
Is every value in the range acceptable to datetime
?
SELECT DateOfAction
FROM ResAdm.Action
WHERE cast(DateOfAction as DATE) < '17530101'
回答4:
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 have datetime2
, which will work a lot better.
来源:https://stackoverflow.com/questions/4682377/conversion-of-varchar-into-datetime