简体   繁体   English

SQL Server Where子句

[英]SQL Server Where Clauses

When running a select query (on SQL SERVER 2000+) with multiple where statements such as 当运行带有多个where语句的select查询(在SQL SERVER 2000+上)时,例如

SELECT    * 
FROM      TABLE1
WHERE     TableId = @TableId 
          AND Column1 = @Column1 
          AND Column2 = @Column2 
          AND Column3 = @Column3 etc.

...does the query calculate each and every one of the where clauses even if the first one does not equate? ...即使第一个子句不相等,查询也会计算where子句中的每个子句吗? I have a query which checks each of the columns to see if any changes have been made, before updating (ie it only updates if there are changes). 我有一个查询,它在更新之前检查每一列,以查看是否进行了任何更改(即,仅在有更改的情况下才进行更新)。 If the query compares every column then I think I will need to rewrite the query. 如果查询比较每一列,那么我想我需要重写查询。 However, if the query engine first filters to the ID column and then compares each column individually within that filtered set the performance should be fine (I would have thought?). 但是,如果查询引擎首先过滤到ID列,然后在该过滤后的集合中分别比较每个列,则性能应该不错(我会想到吗?)。

I hope that makes sense. 我希望这是有道理的。

Thanks, James. 谢谢,詹姆斯。

Based on statistics and available indexes, the optimiser will estimate which is the best order to compute the query. 基于统计信息和可用索引,优化器将估计哪个是计算查询的最佳顺序。 Most of the time it gets it right, but can be thrown off by out of date statistics. 在大多数情况下,它是正确的,但是可以通过过时的统计信息将其丢弃。

You should not be concerned with the order of WHERE clauses. 您不必关心WHERE子句的顺序。 Rather, have a look at the actual execution plan created for the query. 而是查看为查询创建的实际执行计划。

No. 没有。

The query engine is pretty well optimised. 查询引擎进行了很好的优化。

why hit the data twice with something like: 为什么用类似以下命令两次击中数据:

--did data change?
if exists (select ... where pk=@pk and and and...)
begin
    update ... where pk=@pk
end

just do something like: 只是做类似的事情:

update ... where pk=@pk and and and...

you can check @@ROWCOUNT if you need to know if it actually changed and was UPDATEd 您可以检查@@ ROWCOUNT是否需要实际更改和更新

I dont know if this will be possible in your case but try this: 我不知道这种情况是否可行,请尝试以下操作:

On the table/data set you are looking at, create a LastModified datetime default getdate() column. 在要查看的表/数据集上,创建一个LastModified datetime默认getdate()列。 Then create a trigger for Update to that table. 然后为该表的更新创建一个触发器。 Make the trigger do the following. 使触发器执行以下操作。

On update set LastModified = getdate() 在更新集LastModified = getdate()

This is good database design, and you can index the LastModified column. 这是很好的数据库设计,您可以索引LastModified列。 This is a narrower index to maintain and your query can now be 这是一个较窄的索引,需要维护,您的查询现在可以

UPDATE... WHERE LastModifed >= @LastRunDate

For help on triggers, try this Stack overflow thread: Trigger Firing 要获取有关触发器的帮助,请尝试以下堆栈溢出线程: Trigger Firing

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

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