Using IF in T-SQL weakens or breaks execution plan caching?
Posted
by AnthonyWJones
on Stack Overflow
See other posts from Stack Overflow
or by AnthonyWJones
Published on 2010-04-26T12:15:36Z
Indexed on
2010/04/26
12:23 UTC
Read the original article
Hit count: 247
It has been suggest to me that the use of IF statements in t-SQL batches is detrimental to performance. I'm trying to find some confirmation of this assertion. I'm using SQL Server 2005 and 2008.
The assertion is that with the following batch:-
IF @parameter = 0
BEGIN
SELECT ... something
END
ELSE
BEGIN
SELECT ... something else
END
SQL Server cannot re-use the execution plan generated because the next execution may need a different branch. This implies that SQL Server will eliminate one branch entirely from execution plan on the basis that for the current execution it can already determine which branch is needed. Is this really true?
In addition what happens in this case:-
IF EXISTS (SELECT ....)
BEGIN
SELECT ... something
END
ELSE
BEGIN
SELECT ... something else
END
where it's not possible to determine in advance which branch will be executed?
© Stack Overflow or respective owner