日期:2014-05-18  浏览次数:20451 次

DATETIME OR VARCHAR
SQL code

declare @a datetime
select @a=year(getdate())
select @a
go
declare @a varchar(20)
select @a=year(getdate())
select @a


-----------------------
1905-07-06 00:00:00.000

(1 行受影响)


--------------------
2012

(1 行受影响)





这是为啥阿,结果不一样。变成1905年了。

------解决方案--------------------
第一个:
declare @a datetime 定义日期类型变量@a
select @a=year(getdate()) 给日期@a赋值 @a = 2012相当于 @a = DATEAdd ( day , 2012 , '1900-01-01' )
select @a 所以返回值应该是DATEAdd ( day , 2012 , '1900-01-01' )

第二个:
declare @a varchar(20) 定义可变字符串类型变量@a
select @a=year(getdate()) 给字符串赋值 @a = 2012
select @a 所以返回值就是2012