In SQL Server 2012, I have a big query that have this where clause:
(1 = Case
When (@bSomeSpecialCheck = 'Y') Then
Case When (dbo.SomeFunction(SomeColumn, @SomeParam)=1) Then 1 Else 0 End
Else 1 End)
I know that “SomeFunction” is a slow one, and I want that to be evaluated only if there is a value in @SomeParam. So I wrote the where this way, because I want to avoid the execution of “SomeFunction” if not needed.
Well, the thing is that regardless @bSomeSpecialCheck is always “N”, it seems that SQL Server is evaluating the whole Case, because if I write it this way for testing purposes:
(1 = Case
When (@bSomeSpecialCheck = 'Y') Then
Case When (1=1) Then 1 Else 0 End
Else 1 End)
I get an immediate response, so I know that my slow function “SomeFunction” is being evaluated, but why?
How can I avoid the evaluation of SomeFunction only when @bSomeSpecialCheck is “Y”?
I think the only way to avoid this is to duplicate your query