SSRS 2008 - Dealing with division by zero scenarios

后端 未结 4 1770
北海茫月
北海茫月 2020-11-30 07:16

We\'re running into a problem with one of our reports. In one of our tablixes a textbox has the following expression:

=Iif(Fields!SomeField.Value = 0, 0, Fie         


        
相关标签:
4条回答
  • 2020-11-30 07:46

    IIf will always evaluate both results before deciding which one to actually return.

    Try

    =IIf(Fields!SomeField.Value = 0, 0, Fields!SomeOtherField.Value / IIf(Fields!SomeField.Value = 0, 1, Fields!SomeField.Value))
    

    This will use 1 as the divisor if SomeOtherField.Value = 0, which does not generate an error. The parent IIf will return the correct 0 for the overall expression.

    0 讨论(0)
  • 2020-11-30 07:52

    An easy clean way to prevent a divide by zero error is using the report code area.

    In the Menu, go to Report > Report Properties > Code and paste the code below

    Public Function Quotient(ByVal numerator As Decimal, denominator As Decimal) As Decimal
            If denominator = 0 Then
                Return 0
            Else
                Return numerator / denominator
            End If
        End Function
    

    To call the function go to the the Textbox expression and type:

     =Code.Quotient(SUM(fields!FieldName.Value),SUM(Fields!FieldName2.Value))
    

    In this case I am putting the formula at the Group level so I am using sum. Otherwise it would be:

     =Code.Quotient(fields!FieldName.Value,Fields!FieldName2.Value)
    

    From: http://williameduardo.com/development/ssrs/ssrs-divide-by-zero-error/

    0 讨论(0)
  • 2020-11-30 07:58

    IIF evaluates both expression even thought the value of Fields!SomeField.Value is 0. Use IF instead of IIF will fix the problem.

    0 讨论(0)
  • 2020-11-30 08:05

    On reflection, I feel best idea is to multiply by value to power -1, which is a divide:

    =IIf
      (
          Fields!SomeField.Value = 0
        , 0
        , Fields!SomeOtherField.Value * Fields!SomeField.Value ^ -1
      )
    

    This doesn't fire pre-render checks as val * 0 ^ -1 results in Infinity, not error

    0 讨论(0)
提交回复
热议问题