SQL SERVER查询时间条件式的写法

数据库 SQL Server
SQL SERVER查询时间条件式应该如何写呢?这是很多人都提到的问题。下文就将带您寻找其中的答案,希望对您能有所帮助。

查询是SQL SERVER的核心功能,下面就为您详细介绍SQL SERVER查询时间条件式的写法,如果您对此方面感兴趣的话,不妨一看。

如下表:

tid   tname tdate
1      张三        2009-10-29 19:04:50
2      李四        2006-11-12 11:04:50
3      王五        2007-6-11
4      陈六        2007-8-26 12:04:50
5      小二        2009-11-28

下面开始做各种时间查询:注意:避免在WHERE条件式中对字段做运算,比如convert(char(10),tdate,120)

select tname from tt Where tdate='2007-06-11' --当时间段值为2007-06-11 00:00:00.000时,此条件式成立

--select tname 时间值没有 from tt Where tdate='2007-08-26' --时间段值为2007-08-26 12:04:50.000,此条件式不成立,时间值不同,这样找不到当天值
select tname 查找当天时间 from tt Where tdate between '2007-08-26 00:00:00' and '2007-08-26 23:59:59'
--select tname 今天的值 from tt Where tdate =getdate() --不行,因为SQL会默认当天起点是00:00:00开始,

select tname 今天的值方式一 from tt Where tdate between convert(char(10),getdate(),120) and convert(char(10),getdate(),120)+' 23:59:59'
select tname 今天的值方式二 from tt Where tdate >= convert(char(10),getdate(),120) and tdate<convert(char(10),getdate()+1,120)

--select tname from tt Where left(tdate,10)='2007-06-11' --

--select tname from tt Where convert(char(10),tdate,120)='2007-06-11' --查找当天值,可以用,但效率低

--select tname aa from tt Where convert(char(10),tdate,120)='2007-08-26' --查找当天值,可以用,但如果条件式后面为‘2007-8-26’则不行.因为char(10)限定十位

--select tname 时间 from tt Where tdate Like '2007-08-26%' --不可用,找不到记录
--select tname 时间段 from tt Where tdate between '2007-06-11' and '2007-09-12'

查找时间段也是一样的,如:

select tname 查找2007年6月11号到8月26的记录 From tt Where tdate >='2007-06-11' and tdate<= '2007-08-26 23:59:59'

以上就是SQL SERVER查询时间条件式的写法介绍。

 

 

【编辑推荐】

SQL Server查询结果集中的常量

sql server查询字段详细信息

SQL Server FROM子句的语法

SQL Server字符串函数大全

SQL Server绑定连接

责任编辑:段燃 来源: 互联网
相关推荐

2010-09-14 16:36:34

SQL SERVER查

2019-06-27 10:35:40

JavaScript条件式匹配条件

2010-09-25 16:42:45

sql语句

2010-09-24 19:23:51

SQL查询时间段

2010-11-09 15:18:37

SQL Server多

2009-03-23 10:47:43

数据库SQLLINQ

2010-10-21 11:10:57

SQL Server查

2010-07-06 09:39:20

SQL Server分

2010-10-21 14:27:35

SQL Server时

2010-09-10 08:54:02

2010-09-13 13:44:22

sql server外

2010-11-09 16:20:46

SQL Server死

2021-01-19 05:39:17

SQLServer变量

2010-09-28 11:28:40

SQL字段属性

2011-04-06 13:38:11

SQL ServerSQL语句

2010-11-09 15:30:01

Sql server时

2010-09-26 16:56:14

sql语句

2010-10-21 12:16:11

SQL Server查

2010-07-12 17:12:48

SQL Server数

2021-08-17 10:39:54

SQL Server数据库优化
点赞
收藏

51CTO技术栈公众号