日期:2014-05-19  浏览次数:20479 次

case 作查询条件问题
我想这样设定查询条件:
@iPrice=1   那么价格在0-500之间
@iPrice=2   那么价格在500-1000之间
@iPrice=3   那么价格在1000以上

SELECT   GoodsName   FROM   GoodsData  
case   when   @iPrice=1   then   SoftPrice> 0   and   SoftPrice <501   when   @iPrice=2   then   SoftPrice <1001   and   SoftPrice> 500   when   @iPrice=3   then   SoftPrice> 1000   end

结果出现提示:   '> '附近有语法错误,请问是怎么回事?难道一定要用   if   else   ?

------解决方案--------------------
貌似不能做查询条件吧,不如这样写:

SELECT GoodsName FROM GoodsData
where @iPrice=1 and SoftPrice betweem 0 and 500
or @iPrice=2 and SoftPrice between 501 and 1000
or @iPrice=3 and SoftPrice > 1000


或者干脆这样写:
SELECT GoodsName FROM GoodsData where @iPrice=1 and SoftPrice betweem 0 and 500
union all
SELECT GoodsName FROM GoodsData where @iPrice=2 and SoftPrice between 501 and 1000
union all
SELECT GoodsName FROM GoodsData where @iPrice=3 and SoftPrice > 1000

------解决方案--------------------
用case也是可以的,case 用于句中时只是作为函数用,必然是一个值,值能用的地方它才能用
SELECT GoodsName FROM GoodsData where
SoftPrice between (case @iPrice when 1 then 1 when 2 then 501 else 1001 end) and (case @a when 1 then 500 when 1000 then 3 else 999999 end)
但coolingpipe(冷箫轻笛)的第一种方法最好(0要改为1)