SQL不允许将日期列强制转换为datetime? [英] SQL doesn't allow to cast date column to datetime?
问题描述
Select *
from tableA
inner join tableB on tableA.id = tableB.aid
and cast(a.date AS DATETIME) = CAST('2015-08-24' AS DATETIME)
存储在中的值tableA.date
是'2015-08-24',表示数据没有问题。
Values that stored in tableA.date
are '2015-08-24' meaning data has no issue.
执行上述语句时,我会得到
When I execute the above statement, I get
将日期数据类型转换为日期时间数据类型会导致超出范围的值
The conversion of a date data type to a datetime data type resulted in an out-of-range value
我可以知道为什么不能将 date
列强制转换为 datetime
?
May I know why cant cast a date
column to datetime
?
推荐答案
问题的根本原因是:
- 数据类型
DATE
的可接受值范围为01-01-0001
到12-31-9999
- 数据类型
DATETIME
的可接受范围是01-01-1753
到12-31-9999
- the data type
DATE
has a range of accepted values from01-01-0001
through12-31-9999
- the data type
DATETIME
has a range of accepted values from01-01-1753
through12-31-9999
因此,如果您碰巧有1753年之前的 DATE
,或一个空/ NULL值-这将超出 DATETIME
可以处理的范围。
So if you happen to have a DATE
from before 1753, or an empty / NULL value - this will be outside the range that DATETIME
can handle.
您应停止使用 DATETIME
在SQL Server 2008 及更高版本中。使用 DATETIME2(n)
代替(其中 n
代表所需的小数秒)。
You should stop using DATETIME
In SQL Server 2008 and newer. Use DATETIME2(n)
instead (where n
stands for the number of fractional seconds you need).
因此,请尝试以下操作:
So try this:
select *
from tableA
inner join tableB on tableA.id = tableB.aid
and cast(a.date AS DATETIME2(3)) = CAST('2015-08-24' AS DATETIME2(3))
我确信这会很好。
这篇关于SQL不允许将日期列强制转换为datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!