> SELECT ....
> FROM ....
> WHERE (@ReturnTimedOrNotTimed IN ('N', 'B') AND PickupTime IS NULL)
> UNION
> SELECT ...
> FROM ...
> WHERE (@ReturnTimedOrNotTimed IN ('T', 'B') AND
> PickupTime IS NOT NULL)
"Erland Sommarskog" <esquel@sommarskog.se> wrote in message
news:Xns98AB73AED4AFBYazorman@127.0.0.1...
> Keith G Hicks (krh@comcast.net) writes:
>> I'd rather avoid restating the entire query 3 times and I know I should
>> avoid dynamic sql where possible. I've been trying to figure out how to
>> put the @ReturnTimedOrNotTimed for all 3 cases in the WHERE part of one
>> query but what I tried slows it down a lot (3 times slower).
>
> These types of searches often gets the best performance with dynamic SQL,
> but if there is only one parameter I would probably not go for dynamic SQL
> myself.
>
> Here is a variation that only requires you to repeat the query twice:
>
> SELECT ....
> FROM ....
> WHERE (@ReturnTimedOrNotTimed IN ('N', 'B') AND PickupTime IS NULL)
> UNION
> SELECT ...
> FROM ...
> WHERE (@ReturnTimedOrNotTimed IN ('T', 'B') AND
> PickupTime IS NOT NULL)
>
>> I get the result set I expect for each value of @ReturnTimedOrNotTimed
>> but again, it's much slower than the first way. Is there a good way to
>> write a where clause that depends on an input parameter like this? I
>> tried a CASE construct in the WHERE but couldn't get it to even compile.
>> Not sure if that's possible.
>
> Nigel's post gave you the syntax for CASE, but I would not expect this
> to perform any better. The problem is that as soon you put that open-
> ended variable, the query plan must cover all possible values for it,
> since the value of the variable is not known to the optimizer when the
> plan is built. (Parameter sniffing? Yes, the value can be used as
> guidance, but the optimizer must build a plan which still produces the
> correct result if the parameter is changed along the way.)
>
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
>
> Books Online for SQL Server 2005 at
>
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx > Books Online for SQL Server 2000 at
>
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx