现在2段sql代码,我想都优化为一段代码(为了不写重复的代码),或者是一个函数,代码如下:
declare @a int,@b int 
if @a = 1
   select * from Table1 where b = @b
else if @a = 2
   select * from Table2 where b = @bdeclare @a int,@b int ,@c int 
if @a = 1
   select * from Table1 where b = @b
else if @a = 2
   select * from Table1 where c = @c
else if @a = 3
   select * from Table1 where a = @a and b = @b and c = @c 
请问如何才能优化为一段代码(为了不写重复的代码)呢?

解决方案 »

  1.   

    a=2时,table1和table2是按一条select出来,还是两条,也就是说用不用union all连接的
      

  2.   

    使用函数本来就会导致优化器无法很好的优化(看执行计划就知道)
    重复写代码会好一些, 优化器可以直观知道你想干嘛, 并据此选择出比较优化的执行计划
    这就类似于通过层层封装后的 Framework 越来越好用, 但越来越慢
      

  3.   


    --第1个用动态sql就可以了
    declare @a int,@b int 
    declare @sql varchar(100)
    set @sql=isnull(@sql,'')+'select * from Table'+cast(@a as varchar(1))+' where b='''+@b+''''
    exec(@sql)第二个要整成一条sql语句不容易
      

  4.   

    这样的话,写sql的时候,编译器就无法检测代码了呀,还有更好的方法吗
      

  5.   

    上面是不同的2个代码段。我的意思就是能不能分别对这2个代码用进行优化,用一条sql语句写出来
      

  6.   

    declare @a int,@b int ,@c int 
    if @a = 1
       select * from Table1 where b = @b
    else if @a = 2
       begin
              select * from Table1 where c = @c
              select * from Table2 where b = @b
       end
    else if @a = 3
       select * from Table1 where a = @a and b = @b and c = @c 不是代码看起来少才好。