I am trying to find the best way to use a conditional statement in my WHERE clause based off a parameter.
The statement should be 'if @AvailQtyOperator = 1 then {bring me back data where} id.AvailableQuantity > @AvailQtyValue'
If @AvailQtyOperator = 1 means greaterThan So I am wanting to only select data where AvailableQuantity is greater than the incoming parameter @AvailQtyValue
I am uncertain if CASE is the best choice for this. Any direction would be appreciated.
Here is what I have tried so far but can't find the right syntax:
SELECT id.PK_Import,
id.importDate,
id.AvailableQuantity
FROM Import id
WHERE
((id.ImportDate >= @ImportDateFrom OR @ImportDateFrom IS NULL) AND
(id.ImportDate <= @ImportDateTo OR @ImportDateTo IS NULL)) AND
/* Below is the problem */
(CASE WHEN @AvailQtyOperator = '1' then
id.AvailableQuantity > @AvailQtyValue END)
(CASE WHEN @AvailQtyOperator = '2' then
id.AvailableQuantity < @AvailQtyValue END)
(CASE WHEN @AvailQtyOperator = '3' then
id.AvailableQuantity = @AvailQtyValue END)
(CASE WHEN @AvailQtyOperator = '4' then
id.AvailableQuantity <> @AvailQtyValue END)
3条答案
按热度按时间x6yk4ghg1#
You can just use normal boolean logic. Note that
AND
has a higher precedence thanOR
.Having said that, this is going to be highly inefficient. You are better off building a dynamic query that will do the correct conditions. You should still pass the parameters in properly using
sp_executesql
. This type of query is called a Kitchen Sink Query.jljoyd4f2#
lhcgjxsq3#
The
CASE
statement in the above code will return a value that isnot NULL
if the value of the @AvailQtyOperator
parameter is equal to one of the values in the list. If the value of the @AvailQtyOperator
parameter is not equal to any of the values in the list, theCASE
statement will return a value that isNULL
.The
WHERE
clause in the above code is used to filter the rows where theCASE
statement returns a value that isnot NULL.