Using IF in T-SQL weakens or breaks execution plan caching?
- by AnthonyWJones
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?