简体   繁体   English

SQL Server 2008日期时间类型时间比较

[英]SQL Server 2008 datetime type time comparison

Is the following query the most inefficient way to filter by only the time part datetime field in SQL Server 2008? 以下查询是否仅通过SQL Server 2008中的时间部分datetime字段进行过滤的效率最低?

SELECT *
FROM mytable
WHERE CAST([DATEEND] as TIME ) > "5:00PM";

Are there any major caveats or performance issues in doing the type casting in the where statement? 在where语句中进行类型转换是否有任何重大警告或性能问题?

Are there any better alternatives or best practices? 有没有更好的选择或最佳做法?

The main issue with this query is that it is unsargable. 此查询的主要问题是它不可更改。 Even if the DATEEND column is indexed then the index cannot be used. 即使DATEEND列已建立索引,也无法使用该索引。

The only way of making this query index friendly would be to have an computed column with definition CAST([DATEEND] as TIME) and then index it. 使该查询索引友好的唯一方法是使计算列的定义为CAST([DATEEND] as TIME) ,然后对其进行索引。

Even if you were to do that you may well find that the index isn't used though as it will depend how selective the query is. 即使您这样做,也很可能会发现未使用索引,因为它取决于查询的选择性。 As your query uses * the index will need to do key lookups to retrieve the non covered columns. 当您的查询使用* ,索引将需要进行键查找以检索未覆盖的列。 The exact selectivity at which the index would be used depends on the "Tipping Point" 使用索引的确切选择性取决于纸点”

You could also make the index covering by INCLUDE -ing the missing columns but as you are selecting all columns in the table that will make the index very wide which means more logical reads to scan it as well as more expensive to maintain for data modification statements. 您还可以通过INCLUDE覆盖缺少的列来使索引覆盖-但是在选择表中的所有列时,这将使索引非常宽,这意味着要扫描索引需要进行更多的逻辑读取,并且对于数据修改语句而言维护成本更高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM