We have an SP with a big select statement with a huge where clause with about fifty conditions which is NOT the way you really want to write things but there it is. The odd thing is just one small condition, something like:
where ( exists(select 1 from #foo where myfield = e.myfield) or exists(select 1 from #foo where myfield is null) )
#foo is a small table with just one field and typically a handful of rows. When there is any valid value myfield must have non-null values. When we want to turn off the condition #foo has just one row with a null value, explaining this code. BTW I also tried a variety of rewrites substituting a @match_all constant for the second exists(), nothing helped.
The problem - that is, the opportunity - is that if I comment out the "or exists(select 1 from #foo where myfield is null)" then the entire select statement with all fifty conditions runs about 30x faster when there are valid entries in #foo. When there are NOT valid entries in #foo, just the one null row, it doesn't matter that there are two exists conditions, that part runs OK.
So, why would the two exists conditions be so dramatically slower than just the one? This is a variety of the old "where (@foo is null or x.foo = @foo) problem, but I can't seem to find a rewrite or option(optimize) that fixes this one.
Ideas?
Thanks,
Josh