May 24, 2010 at 8:20 pm
College of mine tells me that IF statement in stored procedure is not a good idea becuase:
1) it either recompiles stored proc on every use
2) or the sql statement inside the "if" are not cached etc...
Is any of this true. Anoterword, is there any downside in using IF statement in SQL stored proc.
Thanks for your help.
May 25, 2010 at 1:15 am
I believe your colleague is referring to this:
http://sqlinthewild.co.za/index.php/2009/09/15/multiple-execution-paths/
You should be aware of the concept, but don't draw any unshakeable conclusions - there are very few absolutes in SQL Server and whether to use IF or not is not one of them. Consider each instance on its merits, and be sure to fully understand what is going on and why.
See the following MSDN article for a full background. You must read this to understand.
http://technet.microsoft.com/en-us/library/cc966425.aspx
Paul
May 25, 2010 at 1:39 am
spatemp (5/24/2010)
1) it either recompiles stored proc on every use2) or the sql statement inside the "if" are not cached etc....
Neither is true.
What you can get is a form of parameter sniffing. If certain branches if will only be executed for certain parameter values, you can get a case where, if the first compile of the proc has other parameter values, the exec plan for some branches will be a poor one.
It's not a problem with IF statement per se. It has to do with the way the entire proc is compiled and the resulting plan cached, and the parameter sniffing that the optimiser does.
You absolutely cannot make a blanket statement that IF statements are bad. There are certain constructs using if statements that are prone to poor execution plans, that's all.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
May 25, 2010 at 1:52 am
In case you hadn't noticed, that was Gail's blog entry that I pointed you at
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy