if @a='0'
 select * from tb ;
else 
 select * from tb where c1='100';上面这个语句可不可以改成
select * from tb where c1=case when @a='0' then '100' else c1 end 
暂时不考虑null的情况
为什么上面两种的性能不一样?
求解译。难道优化器不知道@a是个变量?它也可以一下就计算出来了啊?
这是怎么回事。谢谢。

解决方案 »

  1.   

    性能肯定是if else快,应该这个只做一次判断,然后给结果,where语句是在判断中筛选结果,所以肯定性能差。SQL还没那么智能啊
      

  2.   

    接楼上
    而且select * from tb 和select * from tb where c1 = c1
    执行效率也不是一样的,后者会先把结果集放入临时表中,然后在判断一次恒等的。
      

  3.   

    select * from tb where 
    (case when @a='0' then 1 else c1 end)=
    (case when @a='0' then 1 else '100' end)这样写 怎么样
      

  4.   

    case when 和要表达的意思写反了..
      

  5.   

    select * from tb where c1=case when @a='0' then '100' else c1 end主要因为有这个.你看执行计划就很清楚了.
      

  6.   

    怎么会不一样的? 难道select * from tb where 1=1也不一样? mysql里无条件的生成的都是 where 1=1
      

  7.   


    --不考虑null的情况
    create table tb (c1 int)
    insert into tb 
    select number from master..spt_values 
    where type='p' and number between 1 and 150gocreate proc test1 (@a varchar(10))
    as
    begin
    if @a='0'
     select * from tb ;
    else 
     select * from tb where c1='100';
    end
    go
    create proc test2 (@a varchar(10))
    as
    begin
    select * from tb 
    where c1=case when @a='0' then c1 else '100' end  
    end
    go
    create proc test3 (@a varchar(10))
    as
    begin
    select * from tb where @a='0' or (@a<>'0' and c1='100')
    end--测试
    exec test1 '1' --50%
    exec test2 '1' --25%
    exec test3 '1' --25%
      

  8.   

    select * from tb where (@a='0' and 1 = 1) or (@a <> '0' and c1 = '100')
      

  9.   

    test2 受null的制约,需要加上isnull做判断,就不如test3了。