SQL Server - Query Execution Plan For Conditional Statements

陌路散爱 提交于 2019-12-12 14:32:02

问题


How do conditional statements (like IF ... ELSE) affect the query execution plan in SQL Server (2005 and above)?

Can conditional statements cause poor execution plans, and are there any form of conditionals you need to be wary of when considering performance?

** Edited to add ** :

I'm specifically referring to the cached query execution plan. For instance, when caching the query execution plan in the instance below, are two execution plans cached for each of the outcomes of the conditional?

DECLARE @condition BIT

IF @condition = 1
BEGIN
    SELECT * from ...
END
ELSE
BEGIN
    SELECT * from ..
END

回答1:


You'll get plan recompiles often with that approach. I generally try to split them up, so you end up with:

DECLARE @condition BIT

IF @condition = 1 
BEGIN 
 EXEC MyProc1
END 
ELSE 
BEGIN 
 EXEC MyProc2
END

This way there's no difference to the end users, and MyProc1 & 2 get their own, proper cached execution plans. One procedure, one query.



来源:https://stackoverflow.com/questions/289625/sql-server-query-execution-plan-for-conditional-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!