Hi,
I have a below query.
Select * from Employees(NOLOCK) Where HomeCountry = 'USA' AND
HostCountry = 'JAPAN'
In some places i want to use 'OR' in place of 'AND' in the WHERE
Clause based on one Flag ANDORFLAG.
IF ANDORFLAG = 1 THen i want to use 'AND' in the WHERE CLAUSE.
IF ANDORFLAG = 0, THEN i want to use 'OR' in the WHERE CLAUSE.
I tried so many combinations using the CASE, but none of them is
working. Could you please help me how can i achieve this. Below is the
one of the example i tried.
select * from #temp where HomeCOuntry = @ShadowPayrollCountry
case @andorflag when 0 then @and
when 1 then @or end
HostCOuntry = @ShadowPayrollCountry
Tom Cooper - 21 Jul 2008 08:57 GMT
For this case, I would just use an IF, because it is simple, easy to
maintain, and likely to help the Query Optimizer generate an effective query
play, e.g.,
If @AndOrFlag = 0
Select * From #temp
Where HomeCountry = @ShadowPayrollCountry Or HostCountry =
@ShadowPayrollCountry
Else
Select * From #temp
Where HomeCountry = @ShadowPayrollCountry And HostCountry =
@ShadowPayrollCountry
You cold also use dynamic SQL (see http://www.sommarskog.se/dyn-search.html
for a good discussion of this).
It can be done with a single non-dynamic query, but it would not be a good
idea. One way would be
Select * From #temp
Where (HomeCountry = @ShadowPayrollCountry And HostCountry =
@ShadowPayrollCountry)
Or (@AndOrFlag = 0 And (HomeCountry = @ShadowPayrollCountry Or
HostCountry = @ShadowPayrollCountry))
Tom
> Hi,
>
[quoted text clipped - 17 lines]
> when 1 then @or end
> HostCOuntry = @ShadowPayrollCountry
Gert-Jan Strik - 22 Jul 2008 13:37 GMT
Rajeev,
Parameterizing your query with a flag is not a good idea. Apart from the
fact that it cannot be done easily, it will also make your queries very
messy, hard to read and unlikely to run very fast. If someone else ever
has to change your query, he/she will have a hard time figuring out if
the change can be made without rewriting the whole thing.
Another thing. Your original query will never return rows. Since each
row will only have one value in the HomeCountry column, there cannot be
any row for which HomeCountry is both 'USA' and 'JAPAN'. So if you don't
mean 'USA' OR 'Japan', then I don't know what your query is supposed to
return.

Signature
Gert-Jan
SQL Server MVP
> Hi,
>
[quoted text clipped - 17 lines]
> when 1 then @or end
> HostCOuntry = @ShadowPayrollCountry