[转]关于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的记录 结果查不到
有什么办法吗

解决:

 

create table tb(id varchar(1),riqi datetime)
insert into tb values('A' , '2009-01-22 21:22:22') 
insert into tb values('B' , '2009-01-22 19:21:11') 
insert into tb values('C' , '2009-01-22 23:10:22')
go
--1
select * from tb where convert(varchar(10),riqi,120) = '2009-01-22'  
/*
id   riqi                                                   
---- ------------------------------------------------------ 
A    2009-01-22 21:22:22.000
B    2009-01-22 19:21:11.000
C    2009-01-22 23:10:22.000

(所影响的行数为 3 行)
*/
 
--2
select * from tb where riqi between '2009-01-22 00:00:00' and '2009-01-22 23:59:59'  
/*
id   riqi                                                   
---- ------------------------------------------------------ 
A    2009-01-22 21:22:22.000
B    2009-01-22 19:21:11.000
C    2009-01-22 23:10:22.000

(所影响的行数为 3 行)
*/
 
drop table tb

 

总结:

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

我的代码:

String sql = "Select * from [table] Where date1 between '" + dateTimePicker1.Value.ToShortDateString() + " 00:00:00' and '" + dateTimePicker2.Value.ToShortDateString() + " 23:59:59'";

 

 

来源:http://www.cnblogs.com/huangfr/archive/2011/09/04/2166821.html

 

posted @ 2013-06-05 14:18  Seasons1987  阅读(387)  评论(0编辑  收藏  举报