奇怪的行为()在SQL SERVER与COALESCE使用时

问题描述:

DECLARE @i INT 

SET @i=14 

SELECT COALESCE(@i, GetDate()); 

上面现在返回奇怪的行为()在SQL SERVER与COALESCE使用时

1900-01-15 00:00:00.000 

如果我改变我到11,结果将是

1900-01-12 00:00:00.000 

不应该GETDATE( )返回当前日期时间?

+0

我想你可能对于COALESCE的工作原理有些困惑。如果第一个参数不为空,为什么你会期望任何COALESCE返回第二个参数? – ZLK

+0

它更关心数据类型优先级,然后将int转换为datetime。由于第一个参数不为null,它会看到涉及的优先级或数据类型是什么。然后将第一个非null参数转换为该数据类型 –

data type precedence

When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence.

1900-01-01 + 14是1900年1月15日,你的INT转换为日期时间,因为第二个参数,以聚结的日期时间

+0

谢谢。在我尝试SELECT CAST(@i作为DateTime)之后有意义。 –