SQLServer2008中datetime类型不加引号所引发的问题

2014-11-24 09:55:40 · 作者: · 浏览: 0
SQLServer2008中datetime类型不加引号所引发的问题
SQL引号datetime赋值转换
我写了一条如下的SQL语句:
[sql]
update tb_cf_constructionreg set finishDate = 2013-10-10 where ConstructionRegId = 49
结果运行完对应的finishDate字段变成了:1905-06-17 00:00:00.000
不是我想要的2013-10-10,回头一看只是由于没有给2013-10-10加单引号,如果加上单引号就没有错误了,但是没有单引号运行这句SQL居然也没有报错,还出现了一个莫名其妙的值1905-06-17 00:00:00.000,于是我就想弄清楚这个值与2013-10-10之间有什么关系。于是执行了如下几条SQL,继续探究:
[sql]
update tb_cf_constructionreg set finishDate = 0 where ConstructionRegId = 49
update tb_cf_constructionreg set finishDate = 1 where ConstructionRegId = 49
update tb_cf_constructionreg set finishDate = 2 where ConstructionRegId = 49
发现对应的finishDate字段的值如下:
[ html]
0对应 1900-01-01 00:00:00.000
1对应 1900-01-02 00:00:00.000
2对应 1900-01-03 00:00:00.000
这样一来就简单明了,说明如果没有给finishDate加单引号,就会直接将其转化为int,假设这个int的值是A,然后从1990-01-01开始计算,得到A天后的日期
例如2013-10-10,代表的A是:2013-10-10=1993,也就是这句SQL给finishDate赋值为从1990-01-01之后的第1993天的日期:1905-06-17。
另外我还发现如下SQL:
[sql]
update tb_cf_constructionreg set finishDate = -1+++12 where ConstructionRegId = 49
依然可以被正确执行,-1+++12会被计算得到等于11,最终得到1990-01-12。这种写法居然也可以正确执行,的确让人很诧异。