简体   繁体   中英

If I substitue hardcode 1=0 in a sql server query with a variable it slows way down

Testing a query using hard coded 1=0 and 1=1 values. When I substitute a variable for them the query slows way down. And suggestions?

DECLARE @BoxType int
SET @BoxType = 2

Select blah from table t
INNER JOIN table2 t2
    ON (t2.blah = t.blah AND 1=1 OR t2.blah = t.blah AND 1=0)

-- very fast

rewrite using:

...
INNER JOIN table t
    ON (t2.blah = t.blah AND @BoxType = 2 OR t2.blah = t.blah AND @BoxType = 1)

-- very slow

t2.blah = t.blah AND 1=0 will always be false so can be optimised out at compile time.

If you are saying that the second query is slower when @BoxType <> 1 and you are on SQL Server 2008+ you can try adding OPTION (RECOMPILE) to the query to get the same compile time simplification dependant on the actual value of the variable.

The comments have kind of touched on this. When you say “Where MyField = 1” the DB does not know what rows it will find so has to actually search for them. If there is an index on the field it may be reasonably fast. If there is no index and the table need to be scanned could be very long.

But when you say “Where 1=0” The database knows just from the statement that the condition will always be false and no record will be found so will be blinding fast because it doesn't even need to read the table to return to you an empty result set

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM