TSQL:调整动态查询搜索

TSQL: Tune Dynamic Query Search(TSQL:调整动态查询搜索)
本文介绍了TSQL:调整动态查询搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读调整 TSQL 查询时,我看到了关于避免(或小心)WHERE 子句中的函数的建议.但是,在某些情况下——比如需要从今天开始的动态日期的搜索——我很好奇查询是否可以进一步调整?例如,下面的查询使用当前日期的 DATEADD 函数,它允许用户随时获取过去三十天的正确信息:

In reading on tuning TSQL queries, I've seen advice on avoiding (or being careful) about functions in the WHERE clause. However, in some cases - like searches that require dynamic dates from today's date - I'm curious if a query can be tuned further? For instance, the query below this uses the DATEADD function for the current date, which allows the user at anytime to get the correct information for the past thirty days:

SELECT *
FROM Zoo..Transportation
WHERE ArrivalDate BETWEEN DATEADD(DD,-30,GETDATE()) AND GETDATE()

如果我尝试消除函数DATEADD,我可以声明一个变量来提取那个时间,然后使用存储在变量中的设置值查询数据,例如:

If I try to eliminate the function, DATEADD, I could declare a variable that will pull that time and then query the data with that set value stored in the variable, such as:

DECLARE @begin DATE
SET @begin = DATEADD(DD,-30,GETDATE())

SELECT *
FROM Zoo..Transportation
WHERE ArrivalDate BETWEEN @begin AND GETDATE()

但是,执行计划和统计数据显示的读取、扫描和批处理成本完全相同.

However, the Execution Plan and Statistics show the exact same number of reads, scans and batch costs.

在这些动态数据实例中(例如,使用今天的日期作为起点),我们如何减少或消除WHERE 子句中函数的使用?

In these instances of dynamic data (for instance, using today's date as a starting point), how do we reduce or eliminate the use of functions in the WHERE clause?

推荐答案

where 子句中的函数意味着做一些愚蠢的事情,例如:

Functions in the where clause mean doing silly things like:

WHERE DATEPART(WEEK, ArrivalDate) = 1

WHERE CONVERT(CHAR(10), ArrivalDate, 101) = '01/01/2012'

例如对 where 子句中的起作用,这在大多数情况下会破坏可调整性(换句话说,使索引查找无用并强制进行索引或表扫描).

E.g. functions against columns in the where clause, which in most case destroy sargability (in other words, render an index seek useless and force an index or table scan).

我知道有一个例外:

WHERE CONVERT(DATE, ArrivalDate) = CONVERT(DATE, GETDATE())

但我不会将其用于任何其他场景.

But I would not rely on this for any other scenario.

这篇关于TSQL:调整动态查询搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)