SQL转换日期时间

时间:2010-03-25 17:54:58

标签: sql sql-server sql-server-2005 casting

在SQL Server 2005中,为什么:

PRINT Cast('' AS datetime)

显示:

  

1900年1月1日12:00 AM

我原以为它应该是null

3 个答案:

答案 0 :(得分:9)

这是因为空字符串''不是NULL。如果你这样做:

select Cast(null AS datetime)

输出:

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

(1 row(s) affected)

CAST and CONVERT (Transact-SQL)

  

表示的字符数据   只有日期或时间组件   转换为日期时间 smalldatetime   数据类型,未指定的时间   组件设置为00:00:00.000,和   未指定的日期组件已设置   至1900-01-01。

答案 1 :(得分:6)

空字符串被转换为0,后来被转换为时代日期。

Oracle不同,SQL Server区分NULL和空字符串。

答案 2 :(得分:1)

从实验开始,看起来SQL Server会尝试直接转换为DateTime,并且未能尝试转换为int然后转换为DateTime

PRINT Cast('2009-1-1' AS datetime)
go
PRINT Cast('2009/1/1' AS datetime)
go
PRINT Cast('1.1' AS datetime)
go
PRINT Cast('1/2009/1' AS datetime)
go
PRINT Cast('' AS int)
go
PRINT Cast(' ' AS int)
go
PRINT Cast(0 AS datetime)
go
PRINT Cast('X' AS datetime)
go
PRINT Cast('X' AS int)

输出:

Jan  1 2009 12:00AM
Jan  1 2009 12:00AM
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Jan  1 2009 12:00AM
0
0
Jan  1 1900 12:00AM
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'X' to data type int.