Select *
from tableA
inner join tableB on tableA.id = tableB.aid
and cast(a.date AS DATETIME) = CAST('2015-08-24' AS DATETIME)
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
May I know why cant cast a date
column to datetime
?
We can convert the Date into Datetime in two ways. Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type. Convert() function is used to convert a value of any type to another datatype.
To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.
CAST(expression AS [TIMESTAMP | DATETIME | SMALLDATETIME]) represents a date and timestamp with the format YYYY-MM-DD hh:mm:ss. nnn. This value corresponds to the ObjectScript $ZTIMESTAMP special variable. This statement casts a date and time string to the TIMESTAMP data type.
The root cause of the problem is this:
DATE
has a range of accepted values from 01-01-0001
through 12-31-9999
DATETIME
has a range of accepted values from 01-01-1753
through 12-31-9999
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.
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))
and I'm sure this'll work just fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With