I have a table with various columns in it. I want to run a query on this table that is defined by 2 conditions that rely on 2 parameters,
- When
column_a
has a value thatis non zero
, then set the where condition to becolumn_a = param_1
- When
column_a
has a value thatis zero
, then set the where condition to becolumn_b = param_2
My first attempt at this was the following:
Select * from mytable where column_a = param_1 or column_b = param_2
There is a relation between column_a
and column_b
in that when column_a
is non zero then it will not require the latter part of the query (or column_b = param_2
) but when column_a
is zero then I only want to run the latter part of the query and exclude the first part (column_a = param_1
).
Is something like this possible?
2
Answers
You have to add in a test for whether or not column_a is zero. Then check the appropriate param in each case
If a is zero, then the first clause is always true
If a is nonzero then the second clause is always true
If you need the query to be fast then think about two separate queries combined with UNION ALL:
If
@param_1
cannot be zero then the conditionAND column_a <> 0
can be removed.