将比较运算符传递给WHERE子句

时间:2012-09-23 15:31:57

标签: sql-server-2005 case where-clause

我想使用一个参数来保存比较运算符,例如'=''>''>=',并在where子句中使用" case at then"或者如果声明如下:

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

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