Does IF with a static false condition affect SQL Server performance?

212 Views Asked by At
DECLARE @false bit = 0;
IF @false
    xxxx;

In a stored procedure in SQL Server, if you declare a bit variable, set it to 0, and never change it, then when it's used in an IF, like IF @false, will the compiler simply leave out those blocks of code, or will it always evaluate the Boolean expression and branch? The answer will determine whether all my debug logging code needs to be commented out for production.

2

There are 2 best solutions below

1
On

From experimentation, I've concluded that there is, in fact, a performance degradation, albeit minuscule. By performing many "IF @false = 1 xxx;" statements between time checks, I determined that the compiler wasn't smart enough, even though @false could never be 1, to exclude those statements. Adding many additional "IF @false = 1 xxx;" statements further increased the small delay. Consequently, I will comment out these statements.

0
On

SQL Server compiler will do this variable declaration value checks pretty quickly and you wont notice any difference in performance.

As long as these Extra/unwanted variables are not being evaluated against any tables it shouldn't make any noticeable performance impact.

On a side note, if it is not required the best practice is to take it out or as you suggested comment it out.

Also SQL Server BIT variables needs to be evaluated against 0 or 1 , something like

DECLARE @false bit = 0;
IF (@false = 0)
 BEGIN
    PRINT 'xxxx';
 END

If you try to evaluate bit variable like you would do in c#

IF (@false)    --<-- This will error out
    xxxx;