搜索时,CONVERT()对INDEX有什么影响? [英] What is the affect of CONVERT() on INDEX while searching?

查看:153
本文介绍了搜索时,CONVERT()对INDEX有什么影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SQL Server 2008.我在DateTime列DateFrom上有一个非唯一非聚集索引。我正在根据此列搜索表格。我只是想知道 CONVERT()函数对INDEX的影响见下面:

  Query1: 
SELECT *
FROM myTable
WHERE CONVERT(VARCHAR(10),DateFrom,23)> ='2011-01-01'

Query2:
SELECT *
FROM myTable
WHERE DateFrom> ='2011-01-01 00:00:00.000'

我已检查&发现没有区别。但我认为,因为列是CONVERTED,所以索引可能不会被SQL Server使用,这是正确的吗?



请原谅我,如果这不是一个恰当的问题。

通常,当比较的左侧有一个函数时在WHERE子句中,服务器将无法利用引用列上的索引。



在第一个示例中,没有直接与DateFrom列进行比较。相反,您正在使用列上的功能。当服务器扩展它时,它必须对每个列值执行该函数,并且结果值不会编入索引。因此,没有索引可以用来改进查询。



另外,在第一个示例中,您指出DateFrom列是日期时间列。但是,您将该列转换为字符串并进行字符串比较。因此,服务器不会使用您的日期时间索引。



在第二个示例中,您将直接比较常量值和日期列,以便服务器可以使用索引。服务器将比较右侧的字符串常量转换为日期时间值。但是,它不会在所有情况下使用索引。例如,如果行数很少,服务器可能会决定不使用索引,只扫描几行。

这两个查询可能会产生相同的结果结果集,但它们仍然非常不同。


I am using SQL Server 2008. I have a Non-Unique Non-clustered index on a DateTime Column "DateFrom". I am searching the table based on this column. I just wanted to know the affect of CONVERT() function on INDEX see below:

Query1:
SELECT  *
FROM    myTable
WHERE   CONVERT(VARCHAR(10),DateFrom,23) >= '2011-01-01'

Query2:
SELECT  *
FROM    myTable
WHERE   DateFrom >= '2011-01-01 00:00:00.000'

I have checked & found no difference. But i was thinking that since the column is CONVERTED, so the index may not be used by the SQL Server, is it correct?

Please forgive me, if this is not a proper question.

解决方案

Generally, when you have a function on the left side of the comparison in a WHERE clause, the server will be unable to utilize the index on the referenced column.

In your first example, there is no comparison to the DateFrom column directly. Instead, you are using a function on the column. When the server expands this, it must perform the function on each column value, and the resulting value is not indexed. Therefore, no index can be used to improve the query.

Also, in your first example, you indicated that the DateFrom column is a datetime column. Yet, you're converting the column to a string and doing a string comparison. Hence, the server will not use your datetime index.

In your second example, you are comparing the constant value with the date column directly, so the server may utilize the index. The server will convert the string constant on the right side of the comparison into a datetime value. However, it won't use the index in all cases. For example, if you have a very few number of rows, the server may decide not to use the index and just scan the few rows.

Both queries may yield the same result set, but they are still very different.

这篇关于搜索时,CONVERT()对INDEX有什么影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆