一个table在datetime的字段上建了一个索引,当执行下面语句时发现并没有使用到索引select * from table where datetimeField='2010-1-1'如果更改为下面的语句则能够使用到索引,为什么?
declare @a datetime
set @a='2010-1-1'
select * from table where datetimeField=@a
declare @a datetime
set @a='2010-1-1'
select * from table where datetimeField=@a
select * from table where datetimeField='2010-01-01'
DROP TABLE [tb]
GO
create table tb (a int,b int,c int,d datetime)
insert tb select 1,2,3,'20100101'
union all select 2,3,4,'20100405'
gocreate index idx_tb on tb(d)select * from tb where d='20100101'declare @a datetime
set @a='2010-1-1'
select * from tb where d=@a像这两条小记录,计划中连显示用到索引都没有。我想优化器在作用着。
IF NOT OBJECT_ID('[TB]') IS NULL
DROP TABLE [TB]
GO
CREATE TABLE TB (A INT,B INT,C INT,D DATETIME)
INSERT TB
SELECT TOP 1000 1,2,3,DATEADD(DD,-ROW_NUMBER()OVER(ORDER BY GETDATE()),'20100401')
FROM SYSCOLUMNS A,SYSCOLUMNS B
GO
--将字段D加上索引(非聚集)
CREATE INDEX IDX_TB ON TB(D)
GO
SELECT * FROM TB WHERE D='20100101'
--此查询的计划DECLARE @A DATETIME
SET @A='2010-1-1'
SELECT * FROM TB WHERE D=@A
--此查询的计划
这两个查询都能用到索引
如果你要
select * from table where datetimeField='2010-1-1'
返回所有列,如果是聚集索引的话,会进行聚集查找+有序扫描
嗯,测试了一下,当htl258的那个数据当不超过850条记录的话就不会用索引,只会表扫描. 谢谢