2012-09-23 94 views
3

我想用持有比較運營商如'=''>''>='一個參數,並在使用它在那裏用「的情況下,當再」或if語句聲明類似如下:傳遞比較運營商WHERE子句

WHERE 
case @Operator 
when '=' then (@Amount is null) or (@Amount = 0) or (Amount= @Amount) 
when '>' then (@Amount is null) or (@Amount = 0) or (Amount> @Amount) 
when '>=' then (@Amount is null) or (@Amount = 0) or (Amount>= @Amount)  
END 

回答

1

我相信這會做的伎倆:

WHERE 
    @Amount IS NULL 
    OR @Amount = 0 
    OR Amount = CASE @Operator WHEN '=' THEN @Amount END 
    OR Amount > CASE @Operator WHEN '>' THEN @Amount END 
    OR Amount >= CASE @Operator WHEN '>=' THEN @Amount END; 
+0

感謝。但我想知道是否可以爲運算符['BETWEEN'] [@Amount]和[@ Amount2] – user1692483

+0

再添加一個案例謝謝我自己做了WHERE 或者[@Amount]和CASE [@Operator]之間的金額WHEN'在'THEN [@ Amount2] END – user1692483

+0

@ user1692483之間是金額列INT? –

0
where isnull(@Amount, 0) = 0 
    or (Amount = @Amount and @Operator = '=') 
    or (Amount > @Amount and @Operator = '>') 
    or (Amount >= @Amount and @Operator = '>=')