datetime型如何利用索引

geniuswjt 2011-09-02 01:54:58
RT
datetime型字段col,想查当天数据或者昨天数据如何利用col上的索引?
...全文
556 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
NBDBA 2011-09-04
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 geniuswjt 的回复:]
额,我也知道改成写死的可以
当天或昨天呢?
用变量算出来然后套进去?

引用 8 楼 nbdba 的回复:

其他条件的杜需要类似这样转换,论坛上的代码往往不注意这个问题而使用函数,问问题的也可能觉得用函数简洁,反而认为用函数好
[/Quote]
当天或昨天,把函数放在getdate()而不要放在列上

当天:
where col>=convert(varchar(10),getdate(),120)
AND col<convert(varchar(10),dateadd(day,1,getdate()),120)

昨天:
where col>=convert(varchar(10),dateadd(day,-1,getdate()),120)
AND col<convert(varchar(10),getdate(),120)

其他的可能查询方式我相信你自己可以同样写出。

小金牛儿 2011-09-04
  • 打赏
  • 举报
回复
这个时候就不能用date系列的函数处理了 ,建议 用 比较运算符 > < = 或者 用between吧~
中国风 2011-09-02
  • 打赏
  • 举报
回复
列為聚集索引時,比較高效。
利用索引,在左邊列名時不加其它函數,右連條件時可加,這樣可以用到索引,可查看一下執行計劃
中国风 2011-09-02
  • 打赏
  • 举报
回复
select * from Table where col between '2011-09-01' and '2011-09-01 23:59:59 999'

gw6328 2011-09-02
  • 打赏
  • 举报
回复
col<convert(char(8),getdate(),120) and col>=convert(char(8),dateadd(dd,-1,getdate()),120) --今天的
昨天的就是 -1天与-2天的关系。后面用函数应该不影响吧。
geniuswjt 2011-09-02
  • 打赏
  • 举报
回复
额,我也知道改成写死的可以
当天或昨天呢?
用变量算出来然后套进去?[Quote=引用 8 楼 nbdba 的回复:]

其他条件的杜需要类似这样转换,论坛上的代码往往不注意这个问题而使用函数,问问题的也可能觉得用函数简洁,反而认为用函数好
[/Quote]
NBDBA 2011-09-02
  • 打赏
  • 举报
回复
其他条件的杜需要类似这样转换,论坛上的代码往往不注意这个问题而使用函数,问问题的也可能觉得用函数简洁,反而认为用函数好
NBDBA 2011-09-02
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 geniuswjt 的回复:]
SQL code
--比如col上的索引是datetime时创建的
--那么用到时如果是
select col from tb with(index=索引) where convert(varchar(10),col,120)='2011-09-02'
--那这个索引还有用么?起的到检索效果么?


引用 2 楼 maco_wang 的回复:

select id from t ……
[/Quote]
这不行,改成
select col from tb
where col>='2011-09-02'
AND col<'2011-09-03
'

--小F-- 2011-09-02
  • 打赏
  • 举报
回复
select col from tb with(index=索引) where convert(varchar(10),col,120)='2011-09-02'


有函数 用不了索引的
geniuswjt 2011-09-02
  • 打赏
  • 举报
回复
???
geniuswjt 2011-09-02
  • 打赏
  • 举报
回复
--比如col上的索引是datetime时创建的
--那么用到时如果是
select col from tb with(index=索引) where convert(varchar(10),col,120)='2011-09-02'
--那这个索引还有用么?起的到检索效果么?
[Quote=引用 2 楼 maco_wang 的回复:]

select id from t where num=@num
可以改为强制查询使用索引:
select id from t with(index(索引名)) where num=@num
[/Quote]
-晴天 2011-09-02
  • 打赏
  • 举报
回复
2008 可以用 date 数据类型,就用不着想后面的时间问题了.
叶子 2011-09-02
  • 打赏
  • 举报
回复
select id from t where num=@num
可以改为强制查询使用索引:
select id from t with(index(索引名)) where num=@num
geniuswjt 2011-09-02
  • 打赏
  • 举报
回复
强制索引的话用上了有效果的么?!

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧