SQL NULLIF函数无法解决除数

时间:2013-11-05 08:59:24

标签: sql sql-server-2008 null divide-by-zero

我试图使用NULLIF函数返回NULL值,其中查询的除数结果为零,因此返回除零错误。但是,我在我的声明中包装函数时遇到了麻烦。该语句包含CAST,CASE和SUM函数。我在下面的示例中将函数包装在除数中,但这不起作用,我尝试了其他组合。

cast(
  round(
      cast(
          sum(
              case 
                  when @StuYear=11 AND [Levels of Progress] < 3 then 
                      1 
              when @StuYear=10 AND [Levels of Progress] < 2 then 
                      1
              when @StuYear=9 AND [Levels of Progress] < 1 then 
                      1
          else 
                      0 
              end) as decimal)
/
NULLIF(
cast(
    sum(
        case
            when [Levels of Progress] is NULL then 
                0 
            else 
                1 
        end) as decimal) * 100,1) as numeric(4,1))
,0)

3 个答案:

答案 0 :(得分:1)

Cast(
  Sum(
    CASE WHEN (@StuYear = 11 AND [Levels of Progress] < 3)
           OR (@StuYear = 10 AND [Levels of Progress] < 2)
           OR (@StuYear =  9 AND [Levels of Progress] < 1)
      THEN 1
      ELSE 0
    END
  )
, As decimal)

/

NullIf(
  Cast(
    Sum(
      CASE WHEN [Levels of Progress] IS NULL
        THEN 0
        ELSE 1
      END
    )
  , As decimal)
, 0)

或者我们可以强制Sum()成为NULL,而不是总结&#34;零&#34;。然后,我们的查询的后半部分变为:

Cast(
  Sum(
    CASE WHEN [Levels of Progress] IS NOT NULL
      THEN 1
    END
  )
, As decimal)

顺便提及;如果将来遇到此问题,最好将您的值拆分为单独的列以进行调试。

答案 1 :(得分:1)

您发布的语法无效且难以阅读,您的逻辑似乎也是错误的。

请改为尝试:

declare @stuyear int = 11
select
  cast(
    sum(
      case when @StuYear=11 and [Levels of Progress] < 3 or 
                @StuYear=10 and [Levels of Progress] < 2 or
                @StuYear=9  and [Levels of Progress] < 1 then 1
         else 0 end
     )*100.0 /
    NULLIF(count([Levels of Progress]),0)
  as Numeric(5,2))
from (values (cast(null as int))) x([Levels of Progress])

用您自己的表替换from部分。当count为null时,这是一个有效的语法返回null。

答案 2 :(得分:-1)

为什么不使用TRY ... CATCH并控制代码的流程?

begin try
    print 55/0; -- your code would go here
end try
begin catch
    print Error_Message(); -- do what you need to do here on a divide by zero
end catch