Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL cast datetime

In SQL Server 2005, why does:

PRINT Cast('' AS datetime)

display:

Jan 1 1900 12:00AM

I would have thought it should be null?

like image 870
Ian Vink Avatar asked Mar 25 '10 17:03

Ian Vink


2 Answers

It's because empty string '' is not NULL. If you do:

select Cast(null AS datetime)

OUTPUT:

-----------------------
NULL

(1 row(s) affected)

CAST and CONVERT (Transact-SQL)

When character data that represents only date or only time components is cast to the datetime or smalldatetime data types, the unspecified time component is set to 00:00:00.000, and the unspecified date component is set to 1900-01-01.

like image 146
KM. Avatar answered Nov 04 '22 03:11

KM.


The empty string is casted to 0 which is later casted to the era date.

Unlike Oracle, SQL Server distinguishes between NULL and an empty string.

like image 40
Quassnoi Avatar answered Nov 04 '22 03:11

Quassnoi