Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 

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?

like image 519
SuicideSheep Avatar asked Sep 14 '15 15:09

SuicideSheep


People also ask

Can you CAST date to datetime in SQL?

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.

How do you CAST date and time to date?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.

How do I CAST a timestamp in SQL?

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.


1 Answers

The root cause of the problem is this:

  • the data type DATE has a range of accepted values from 01-01-0001 through 12-31-9999
  • the data type 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.

like image 119
marc_s Avatar answered Nov 08 '22 18:11

marc_s