表中有两个字段A和B
需要在视图中显示A/B的值
但B可能为0,当B为0时,就不计算,直接显示为0该怎样做?

解决方案 »

  1.   

    case when B=0 then 0 else A/B end
      

  2.   

    select case when B=0 then 0 else A/B end as Field1 from Table1 ...
      

  3.   

    case when b=0 then 0 else 1.0*A/B end
      

  4.   


    case when B=0 then 0 
    else 1.0*A/B 
    end
      

  5.   

    http://blog.csdn.net/claro/archive/2009/01/06/3720863.aspx
      

  6.   

    select CASE WHEN B=0 THEN 0 ELSE A/B END FROM 表
      

  7.   


    --设置会话选项
    set ansi_warnings  off
    set arithabort off select isnull(5/0,0)0
      

  8.   

    case when B=0 then 0 else A/B end
      

  9.   

    case when B=0 then 0 else A/B end
      

  10.   

    create table tab(id int,id2 int)
    insert tab
    select 1,2 union 
    select 3,9 union
    select 5,0
    select id,id2,case id2 when 0 then 0 else cast(id as decimal)/id2 end
    from tab
    drop table tab
      

  11.   


    (3 行受影响)
    id          id2         
    ----------- ----------- ---------------------------------------
    1           2           0.50000000000
    3           9           0.33333333333
    5           0           0.00000000000(3 行受影响)
      

  12.   

    注意三点:
    1、除数为零要过了掉,此时使用case判断;
    2、如果除数被除数都是整数时,要注意首先转化为其他类型,否则结果就取整了;
    3、是否需要考虑四舍五入也是要注意的。
      

  13.   


    case when B=0 then 0 else A/B end
      

  14.   

    set ansi_warnings  off
    set arithabort off 
    --设置这两项就可以了
      

  15.   

    case when B=0 then 0 else A/B end
      

  16.   

    select id,id2,case id2 when 0 then 0 else cast(id as decimal)/id2 end
    from tab
    drop table tab