在论坛中出现的比较难的sql问题:46(日期条件出现的奇怪问题)

原文: 在论坛中出现的比较难的sql问题:46(日期条件出现的奇怪问题)

最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。

所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。



关于日期条件出现的奇怪问题。


http://bbs.csdn.net/topics/390498925 

select top 1 ekeyid,ProbeMaterial,Result,LabTestDate from PatientLabTestResults
where ProbeMaterial='Ca'  
  and LabTestDate between convert(datetime,2013/1/1) and
   convert(datetime,'2013/6/24') order by LabTestDate desc

扫描二维码关注公众号,回复: 8149036 查看本文章


这样查的出结果,变成
select top 1 ekeyid,ProbeMaterial,Result,LabTestDate from PatientLabTestResults 
where ProbeMaterial='Ca'  
  and LabTestDate between convert(datetime,2013/1/1) and
   convert(datetime,2013/6/24) order by LabTestDate desc


这样后就查不出结果了,其实只是去除了2013/6/24的'号而已,这个大家能理解是什么问题吗?


   
   
  1. if OBJECT_ID('t') is not null
  2. drop table t
  3. go
  4. create table t(d datetime)
  5. insert into t
  6. select cast( '2013-05-01' as datetime) as d
  7. union all
  8. select cast( '2013-05-10' as datetime)
  9. /*
  10. 1.
  11. 通过查询计划能看出,SQL Server把下面的查询转化成了:
  12. select * from t where d >= convert(datetime,2013/5/1,0) and d <= convert(datetime,'2013/6/24',0)
  13. 也就是查询条件:
  14. d >= convert(datetime,2013/5/1,0) and d <= convert(datetime,'2013/6/24',0)
  15. 进一步转化:
  16. d >= '1901-02-07 00:00:00.000' and d <= 2013-06-24 00:00:00.000
  17. 这样就能查询出结果集。
  18. */
  19. select *
  20. from t
  21. where d between convert(datetime, 2013/ 5/ 1) and convert(datetime, '2013/6/24')
  22. /*
  23. 2.
  24. 通过查询计划能看出,SQL Server把下面的查询转化成了:
  25. select * from t where d >= convert(datetime,2013/5/1,0) and d <= convert(datetime,2013/6/24,0)
  26. 也就是查询条件:
  27. d >= convert(datetime,2013/5/1,0) and d <= convert(datetime,2013/6/24,0)
  28. 进一步转化:
  29. d >= '1901-02-07 00:00:00.000' and d <= '1900-01-14 00:00:00.000'
  30. 由于SQL Server 把2013/6/24中的斜杠,当成了除号,也就是按除法计算了,
  31. 比如:2013/6/24 就等于13,那么由于datetime默认值是默认值: 1900-01-01 00:00:00,
  32. 那么加上13后,就是1900-01-14 00:00:00.000,这样后就查不出结果了.
  33. */
  34. select *
  35. from t
  36. where d between convert(datetime, 2013/ 5/ 1) and convert(datetime, 2013/ 6/ 24)

其实就是,

2013/5/1 就是一个除法运算,结果为402。
2013/6/24 做除法运算后,就是13。


由于datetime数据类型的默认值为:'1900-01-01 00:00:00',

所以上面的convert(datetime,2013/5/1)就是'1900-01-01 00:00:00' 再加上402,
就是'1901-02-07 00:00:00.000',

而convert(datetime,2013/6/24)就是是'1900-01-01 00:00:00' 再加上 13,
就是'1900-01-14 00:00:00.000',

所以就会查不出结果来。


所以,上面的2013/5/1 要写成 '2013/5/1',一定要加上引号。



发布了416 篇原创文章 · 获赞 135 · 访问量 95万+

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12020080.html
今日推荐