SQL Server - Query Execution Plan For Conditional

2019-07-04 21:44发布

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条回答
▲ chillily
2楼-- · 2019-07-04 21:51

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.

查看更多
登录 后发表回答