简体   繁体   English

强制SQL Server首先评估子查询

[英]Force SQL Server to Evaluate Sub Query First

How can I force SQL Server to Evaluate a sub query first? 如何强制SQL Server首先评估子查询?

My query looks something like: 我的查询看起来像:

SELECT ObjectId FROM
(SELECT ObjectId FROM Table Where Id = @Id) T
WHERE fn_LongRunningFunction(T.ObjectId) = 1

I want the outer where clause to evaluate on the result of the inner query. 我希望外部where子句对内部查询的结果求值。 How would I do this without inserting the sub query into a temp table. 我将如何在不将子查询插入到临时表的情况下执行此操作。

When I execute this query SQL evaluates the query as if it where written like: 当我执行此查询时,SQL会对查询进行评估,就像它的编写方式一样:

SELECT ObjectId FROM Table Where Id = @Id AND fn_LongRunningFunction(ObjectId) = 1

which is not what I want. 这不是我想要的。

Why you're even using a sub-query here you could have simply used one query here something like .... 为什么在这里甚至要使用子查询,您在这里都可以只使用一个查询,例如....。

SELECT ObjectId 
FROM Table 
Where Id = @Id
AND fn_LongRunningFunction(ObjectId) = 1

Note 注意

Using a scalar function in where clause as you have will cause a full table scan, Since sql server has to touch every row in the column and execute the function on ObjectId column values to evaluate if it is equal to 1 or not. 在where子句中使用标量函数将导致全表扫描,因为sql server必须触摸列中的每一行并对ObjectId列值执行函数以评估其是否等于1。

Avoid using any functions in where clauses on column names whenever possible. 尽可能避免在列名的where子句中使用任何函数。

for example if you are evaluating a value of a column against a given value do the reverse on the other side of the comparison operator and leave the column alone in where clause, for example if you are looking for values in a table 例如,如果您要针对给定值评估列的值,则在比较运算符的另一侧执行相反操作,并将列留在where子句中,例如,如果您正在表中查找值

WHERE ColumnName + 20 < 100 

Instead of doing you could do something like 除了这样做,您可以做类似的事情

WHERE ColumnName < 100 -20 

In first example sql server will have to touch every row and will add 20 to its value to evaluate it against 100 which will cause a table scan. 在第一个示例中,sql server将必须触摸每一行,并将其值加20以将其评估为100,这将导致表扫描。

In 2nd example if sql server has an index on that column it will simply do a seek to see which values are less then 100 -20. 在第二个示例中,如果sql server在该列上有一个索引,它将简单地进行搜索以查看哪些值小于100 -20。

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

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