时间函数-between

来源:互联网 发布:mac专柜口红价格多少啊 编辑:程序博客网 时间:2024/06/05 23:55


关于SQL中Between语句查询日期的问题

在CSDN找到了相同的问题描述和解决方法:

问题:

我的表某个字段是Datetime型 以" YYYY-MM-DD 00:00:00" 存放 
如 
A 2009-01-22 21:22:22 
B 2009-01-22 19:21:11 
C 2009-01-22 23:10:22 
现在用 select * from TABLE where date between '2009-1-22' And '2009-1-22' 想查日期为2009-1-22的记录 结果查不到 
有什么办法吗

解决:

复制代码
   1: create table tb(id varchar(1),riqi datetime)   2: insert into tb values('A' , '2009-01-22 21:22:22')    3: insert into tb values('B' , '2009-01-22 19:21:11')    4: insert into tb values('C' , '2009-01-22 23:10:22')   5: go   6: --1   7: select * from tb where convert(varchar(10),riqi,120) = '2009-01-22'     8: /*   9: id   riqi                                                     10: ---- ------------------------------------------------------   11: A    2009-01-22 21:22:22.000  12: B    2009-01-22 19:21:11.000  13: C    2009-01-22 23:10:22.000  14:   15: (所影响的行数为 3 行)  16: */  17:    18: --2  19: select * from tb where riqi between '2009-01-22 00:00:00' and '2009-01-22 23:59:59'    20: /*  21: id   riqi                                                     22: ---- ------------------------------------------------------   23: A    2009-01-22 21:22:22.000  24: B    2009-01-22 19:21:11.000  25: C    2009-01-22 23:10:22.000  26:   27: (所影响的行数为 3 行)  28: */  29:    30: drop table tb 
复制代码

总结:

短日期类型默认Time为00:00:00,所以当使用between作限制条件时,就相当于between '2009-1-22 00:00:00'  and '2009-1-22 00:00:00',因此就查不出数据。要想实现功能,那就使用连接字串的形式,在短日期后面把时间补全,那样就能实现功能了。

我的代码:



   1: date1 between '" + dateTimePicker1.Value.ToShortDateString() + " 00:00:00' and '" + dateTimePicker2.Value.ToShortDateString() + " 23:59:59'



2.

 
例如 #05/12/2005# 的前一天和后一天之间: select * from table1 where [date] <=dateadd("d",1,#05/12/2005#) and [date] >=dateadd("d",-1,#05/12/2005#) 例如 #05/12/2005# 的前两个月和后两个月之间: select * from table1 where [date] <=dateadd("",2,#05/12/2005#) and [date] >=dateadd("m",-2,#05/12/2005#)


3.


   1: date1 between '" + dateTimePicker1.Value.ToShortDateString() + " 00:00:00' and '" + dateTimePicker2.Value.ToShortDateString() + " 23:59:59'

最近做了一个有奖答题程序,后台有根据日期查询用户的答题数量,可是遇到了问题,数据库中的内容为

 

IdNameDate1张三2009/4/5 09:13:182李四2009/4/6 15:48:363王五2007/4/7 20:47:58

 

sql查询语句为select * from table where data between '2009-4-5' and '2009-4-5'

查询结果为空

从网上搜索了一下资料 才知道

改为select * from table where data between '2009-4-5' and '2009-4-5 23:59:59'

这样的话就会有一条记录了




   1: date1 between '" + dateTimePicker1.Value.ToShortDateString() + " 00:00:00' and '" + dateTimePicker2.Value.ToShortDateString() + " 23:59:59'
0 0