Data and Analytics with Dustin Ryan

Ssrs expression iif statement divide by zero error.

If you’ve ever tried to use an IIF statement expression to fix an error received by dividing by zero, you probably still received the divide by zero error message. Very frustrating.

An expression like this returns an error when Sum(Fields!Beta.value) = 0:

=sum(Fields!Alpha.Value)/sum(Fields!beta.Value)

So you, being the critical thinker that you are, try the following:

=iif(sum(Fields!Beta.Value)=0,0,sum(Fields!Alpha.Value)/sum(Fields!Beta.Value))

Alas, this will not work. Even though SSRS may evaluate your expression as true, it still will attempt to resolve the false part of your expression, which gives you the divide by zero error.

To get around this infuriating issue Microsoft should have dealt with in the first place, try this:

=iif(sum(Fields!Beta.Value)=0,0,sum(Fields!Alpha.Value)/iif(sum(Fields!Beta.Value)=0,1,sum(Fields!Beta.Value))

This solution should fix any issues you have dividing by zero.

Share this:

3 thoughts on “ssrs expression iif statement divide by zero error”.

thanks for this. You’re missing one last paren though in the final expression.

Hey..thank you so much for saving my time. It worked like a charm!

You’re welcome!

Comments are closed.

Dustin Ryan is a Data Specialist interested in Azure, SQL Server, and Power BI.

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

SSRS Expression Divide by Zero Error

I have a tablix box that has a division expression. When dividing by zero or nulls I get #Error displayed in my report. I tried to create an IIF statement and tested with static values. This verified my syntax was correct but I still see the error on my reports.

Report Preview

=IIF(Sum(Fields!CY_Dollars.Value)=0, 0, (Sum(Fields!CY_Dollars.Value) - Sum(Fields!PY_Dollars.Value))/(Sum(Fields!PY_Dollars.Value)))

So I'm taking Current year dollars, subtracting Previous year dollars, and dividing that total by previous year dollars to get the percentage change. Is there a trick to this that I'm not getting?!

Pedram's user avatar

4 Answers 4

You can add a function to your report code that handles the divide by zero condition, this makes it a bit easier to implement in multiple cells, e.g.

You can then call this in a cell like so:

Nathan Griffiths's user avatar

I suspect you're running into the issue where SSRS doesn't actually short circuit an IIF statement; even though you're checking for 0 , you're still going to hit a divide by zero error.

Try something like:

Using two IIf statements means you avoid the error by using the equation 0/1 when Sum(Fields!PY_Dollars.Value) = 0, thus just returning 0 .

Also note that the above expression is checking Sum(Fields!PY_Dollars.Value) = 0 , but yours is checking Sum(Fields!CY_Dollars.Value) = 0 - the denominator needs the zero check here.

Ian Preston's user avatar

To avoid the overhead of maintaining code, the solution below feels tidiest to me. It avoids the division by zero in the denominator by adding the smallest possible Double value to it ( Double.Epsilon , which is 4.94e-324 ). This value's way too small to affect the value of the fraction for anything people would use SSRS for. It also avoids nesting IIF functions.

ambrosen's user avatar

Why not just express the values as DOUBLE? This avoids the multiple IIF functions? It should have better performance too.

jmoerdyk's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged reporting-services ssrs-tablix ssrs-expression or ask your own question .

Hot Network Questions

reporting services iif divide by zero

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

SSRS Divide by Zero Error

I am getting a divide by zero error in my report and seem to be missing something as to why. The data is below:

I am using the following expression to calculate the average costs per period (note, I also tried Fields!num_costs.Value = 0 ):

My problem occurs with company_2 in period 202010. The expression doesn't seem to be filtering the 0 value in num_costs but it catches the prior NULL value in costs . Below is an example output. Any suggestions on how to modify the expression?

37264-image.png

SQL Server Reporting Services A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports. 2,194 questions Sign in to follow

I came across this which seems to indicate that this is the normal function of IIF in visual basic. I will probably just calculate this in SQL instead of trying to do it in SSRS.

However, I would be interested in seeing if there is a solution to this.

Hi Kottn, @Kottn , It is interesting that this issue should be fixed in newer version of SSRS. I test exact same expression and data in my text environment (SSRS2019 developer edition. And I remember vaguely that this is already fixed in SSRS2017). There is no error appearing.

I think you could try the work around expression like this :

Regards, Joy

If the answer is helpful, please click " Accept Answer " and upvote it. Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread. Users always get connection timeout problem when using multi subnet AG via listener. Especially after failover to another subnet ----Hot issues October

Thanks, I don't think I have permissions to view what version of SSRS I am operating on so that might have been the problem. I am on SQL Server 2017 14.0 for anyone interested in that.

I modified your first expression to consider NULL values in costs and it appears to be working. Thanks!

0 additional answers

Notes to self

Notes to self

my brain dump of solutions to technical problems

SQL Server Reporting Services (SSRS) – IIF statement divide by zero error

If you use the IIF statement to solve your divide by zero errors, you will most likely find that you still get divide by zero errors.

The following example is trying to divide last weeks total hours worked

The following errors:

The Problem Even though the number of days = 0 and it should evaluate to the true condition of 0, SSRS still evaluates the false result, and the false result still throws a divide by zero error because it is evaluating: Sum(Fields!LWTotal.Value) / 0

The solution: We need to try to make the false result not error when working days = 0. The false result

Needs to change to the following:

Why does this work? When working days = 0 the result is going to be 0. So we don’t really care what the false result is going to be we just don’t want it to error. So the new IIF statement on the denominator returns 1 when the working days are zero.

This evaluates to:

and this does not error.

Final Code Example

In short by converting the zero to a 1, it stops the false result from erroring and allows the calculation to work correctly when it is evaluated.

That is a work around for a problem that should never of existed, good one Microsoft..

8 thoughts on “ SQL Server Reporting Services (SSRS) – IIF statement divide by zero error ”

I am using formula for calculated column: =sum(Fields!MarketBetaAdjExp.Value)/sum(Fields!Exposure.Value)

if Field.Exposure = 0 in calculated Column I need show just blank ,what to use?

Apply a format to the field,(by using the format property on the Textbox that the data is being displayed). You can define formats for “positive:Negative:zero”, similar to excel like so;

#0.0;(#0.0);- negative values with this would display as a dash, -.

you should use #0.0;(#0.0);

where there is a single space specified as the zero value.

I just tested it on my report (against 2008 R2 Nov CTP) and it works.

Many thanks, I’ve been scratching my head for weeks about div by 0 errors when I’ve tried to account for them with iif statements.

Awesome post, thanks 🙂

Well done microsoft on this one. Impressive. How could it be that bad.

Thanks for the blog – I was looking for ages to find out what i had done wrong.

Please I need some answeres. Ihave a situation in (Sql reporting services) columns I have two value, One is postive numbers ex(676767)next is (-45623)I have a lot of numbers ,what i need advise I have to sum the negative numbers and devide by another column it hase positive numbers , if any can help me please , I need this very urgent. god bless you

This one was driving me crazy! Thanks for the solution, it worked perfectly.

Thanks! This is the most helpful post I’ve ever found. I would never have figured this one out. You are amazing! Microsoft, not so much on this one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Notify me of follow-up comments by email.

Notify me of new posts by email.

Currently you have JavaScript disabled. In order to post comments, please make sure JavaScript and Cookies are enabled, and reload the page. Click here for instructions on how to enable JavaScript in your browser.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

reporting services iif divide by zero

Insight Extractor – Blog

Paras doshi's blog on analytics, data science & business intelligence., sql server reporting services: how to solve divide by zero errors.

you thought you wrote an if condition to handle “divide by zero” errors in SSRS but still get the run time error?

Example. my expression is:

[code language=”sql”] =IIF(Fields!denominator.Value=0,0, CINT(Fields!numerator.Value/Fields!denominator.Value)) [/code]

Divide by Zero Error SSRS

Note: if you do not have integers to divide and you allow data conversion to double, it would show on SSRS as “infinity” instead of “#Error”.

Let’s understand why does it do it?

So even though you are using IIF condition, the vb IIF condition evaluates every function in every expression before it renders and that’s why the “False” condition that I have in my condition gets run which results in #Error.

Ok, armed with that knowledge, let’s solve the problem.

So here’s a modified version of the expression, have a look:

See what we did there! We added one more IIF condition in the “false” condition of the parent IIF.

[code language=”sql”] =IIF(Fields!denominator.Value=0,0, CINT(Fields!numerator.Value /IIF(Fields!denominator.Value<>0,Fields!denominator.Value,1))) [/code]

Divide by zero fix customer code ssrs

There’s also an alternative to this especially if you have a lot of expressions that does this. You can write your custom code and call it SSRSDIVIDE or you can come up with a better name! Here’s a post that talks about how to do that: http://salvoz.com/blog/2011/11/25/ssrs-checking-for-divide-by-zero-using-custom-code/

Conclusion: In this post, we saw how to solve the divide by zero errors in SSRS.

Share this:

3 thoughts on “ SQL Server Reporting Services: How to Solve Divide by Zero Errors? ”

Thanks. it worked.

That’s great! I am glad this was useful.

This is great. Thank you for the expression. I encountered another problem with the calculation though. Now the partial pallets are returning 0.0 instead of 0.5. Why would this be the case if the formula returning a floating point number?

What do you think? Leave a comment below. Cancel reply

How to Avoid Divide by Zero in Custom Code Function Calls in SQL Server Reporting Services Reports

If you are a developer or if you are dealing with scripting or programming even not professionally, I believe you probably know what kind of an error you will get if you divide a value by zero (0). I know also and I try to avoid divide by zero conditions in reports that I have been developing using the Microsoft SQL Server 2005 / 2008 Reporting Services (SSRS). I always try to check if the divisor is 0 or not. So I have managed to avoid division by zero conditions successfully with the help of " IIF " conditional function. But recently I have realized that if you are using Custom Code and if you are going to call a custom code function if the divisor is not 0 then you should take a step further otherwise report engine again will throw error.

I will try to explain the situation which causes division by zero error with a sample Reporting Services report and a few textbox placed on the layout and edit some expressions for each textbox to demonstrate the problem case.

avoid reporting services divide by zero

GREEN TEXTBOX EXPRESSION WITHOUT CUSTOM CODE FUNCTION CALL OK, the below code is checking the divisor by the help of an IIF control and if the divisor equals to zero (0), then display an empty string on the result field. That is nice but there is not a Custom Code function call in this expression.

RED TEXTBOX EXPRESSION Here is a function build in the Custom Code section of the SQL Server Reporting Services report. Although there is an IIF conditional statement and checks whether the divisor is zero, in the sample you will see that this control is not enough to prevent the textbox expression throw an error. I was hoping the report engine not to evaluate the last part (FALSE part) of the IIF statement, but I realized that although the expression evaluates to TRUE the report engine checks also the FALSE part with the values in each part of the IIF condition.

BLACK TEXTBOX EXPRESSION You can see that the below expression code is same as the above one except the FALSE condition statements of the IIF call. So this expression is our test case to see whether the report server engine error is coming from the Custom Code function call.

GREEN TEXTBOX EXPRESSION And here is what should I do as a Reporting Services report developer to avoid divide by 0 or division by zero cases. You see, I also added a second IIF condition in the parameter section of the Custom Code function call. Here the parameter value is controlled to see that it is different than 0 and then passes an approtiate value in case of the parameter is zero.

So as a summary, to prevent divide by zero errors be carefull with custom functions. If you are calling custom code functions add an additional IIF if required.

SQL Server 2019 Installation download SQL Server 2019 download SQL Server 2017 download SQL Server 2016 download SQL Server 2014 download SQL Server 2012 MacOS ve SQL Server 2019

SQL Resources

SQL Server Tutorials SQL Server 2012 SQL Server Tools SQL Server SSIS

reporting-services

reporting-services IF expression Using IIF to Screen for Division by Zero

Fastest entity framework extensions.

The IIF statement can be used in expressions to screen for division by zero:

SSRS does not short circuit IIF arguments. Therefore, using a single IIF function to screen for division by zero will have no effect and give an #ERROR value.

Instead, a pair of nested IIF statements can be used. The outer IIF controls the value returned in the case of division by zero, 0 in the example above. The inner IIF is a "dummy" value that prevents the engine from actually performing a division by zero in this case.

pdf

Get monthly updates about new articles, cheatsheets, and tricks.

Avoid Divide By Zero Error on SSRS

SSRS functions (as all functions) doesn't like number divided by zero. But, SSRS function behaves weird when they meet an expression that can lead to divide by zero error.

A common report will show the amount of sale compare the target sales. To check if the sales amount meets the target we will divide the sale amount by the target. If one of the store managers on our network haven't entered the planned sale amount yet, it will be zero (on the null) and will cause an error. To keep our report (and gauge) clean, we will try a simple error handling.

For example I used the database ContosoRetailDW. You may download this database from here . I think this database is simpler than AdventureWorks and I prefer to make my demos on it.

I update the target of Amsterdam store and made it zero:

After that I built the query that will be used by the report. The query show sales compare to target for five stores.

I had to use the Union operator instead of join to connect the quota table into the sale table because there could be a store that sold something but doesn't have quota yet and there could be a store that has a quota defined but hasn't sold anything yet.

The Query returned those results:

I have build a report with the expression Amount Sales / Quota to show how well did we meet our goals.

I decide to change the expression and add the IIF condition to help SSRS deal with the divide by zero that make his life harder. I wanted just to tell it, if the quota is zero, don't bother to calculate, just show empty cell. It looks like:

To my surprise, nothing changed.

After I spent some research time I found that SSRS like so much to calculate numbers that it does so even if it's not needed.

In an IF condition expression there are two expressions that only one of them should be shown up, depend on the condition. However, SSRS tries to calculate both the shown expression and the expression that it should not show. In our example, the IIF check and see that sales quota = 0 and that empty cell ( " " ) should be seen . But since it does calculate all the expressions, it also tries to calculate the expression on the FALSE part of the IIF. At that point it again makes the divide by zero error and fail the whole expression as error divide by zero. To avoid that error you should write the formula with two IIF conditions:

Now, all calculations on the expression can be calculated without error. Let's check:

The first IIF:

Quota = 0 –> put "" (empty cell)

Quota <> 0 –> Sale / Quota if Quota <> 0 or Sale / 1 if Quota = 0 . At this point, unlike SSRS we know that quota <> 0 (it was checked on the first IIF) but we have to write it like that to make sure that SSRS will be able to calculate all parts of the IIF while quota = 0.

I think this is not the most efficient way to calculate expressions. Unfortunately SQL Server 2012 reporting services work on the same way.

I have opend a Microsoft connect feedback on that topic. You may vote for it here:

https://connect.microsoft.com/SQLServer/feedback/details/725800/ssrs-iif-function-calculate-both-true-and-false-part-of-the-iif-expresion

Share

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

התגובה שלך *

שמור בדפדפן זה את השם, האימייל והאתר שלי לפעם הבאה שאגיב.

Recent Posts

SSRS: Checking for Divide By Zero Using Custom Code

Friday, november 25, 2011.

I encountered a divide-by-zero error while working on an SSRS report and thought the issue could easily be resolved using IIF with code similar to the following:

I soon realized that this does not resolve the issue.  It appears that all parameters  in the IIF function are evaluated regardless if the first parameter evaluates to true or false.  Therefore, the divide-by-zero was still occurring.

After doing some research, I decided that the best option to avoid the divide-by-zero error is to implement custom code.

Note: The following screen shots are from Report Builder 3.0

The first step is to open the Report Properties window.  You can access the report properties by clicking anywhere outside of the report body.

If you still cannot see the Report Properties window, make sure you have the ‘Properties’ option checked in the ‘View’ tab.

image

The Report Properties window is displayed below.  In the Code text box, click the ellipse […].  You may need to click on the Code text box first to see the ellipse button.

image

Next, select ‘Code’ in the left hand menu if it is not already selected.  Paste the code (displayed below screen shot) in the Custom code field.

SNAGHTML9a4f0b7

Now that you’ve created the custom code, you can begin to use the code in your report.  The following is an example of how you can use the Divide function in a text box expression:

BI Learning Hub

This blog will provide real time solutions in SQL, SSRS, SSIS, DWH, Tableau, Analytics Solution, Agile - Scrum, Salesforce Einstein Analytics (Tableau CRM) and many more. Keep Learning!

Divide by Zero error in SSRS reports

Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing Msbi Training Msbi Online Course

Tableau interview questions and answers for experienced professionals

  Tableau Interview Questions and Answers for experienced professional 1. What is TABLEAU? Tableau  is the powerful and fastest visualizing ...

IMAGES

  1. How to Avoid Divide by Zero in Custom Code Function Calls in SQL Server Reporting Services Reports

    reporting services iif divide by zero

  2. reporting services

    reporting services iif divide by zero

  3. reporting services

    reporting services iif divide by zero

  4. reporting services

    reporting services iif divide by zero

  5. Multiple IIF in an Expression in SSRS

    reporting services iif divide by zero

  6. reporting services

    reporting services iif divide by zero

VIDEO

  1. Froedtert Community Hospital

  2. BIM sord: TELEKOM MALAYSIA

  3. Legend naver die #pkxd #pkxduniverse #shorts

  4. Alcorn State Film Breakdown

  5. Dhaniya Achara Se Kala Tani Khabar||#khesarilalyadav||#kajalraghwani||#newbhojpuristatusvideo

  6. Story of Mother and Daughter Will Make you Cry

COMMENTS

  1. SSRS Expression Iif Statement Divide by Zero Error

    If you've ever tried to use an IIF statement expression to fix an error received by dividing by zero, you probably still received the divide

  2. SSRS Expression Divide by Zero Error

    SSRS Expression Divide by Zero Error · You mentioned that there are nulls in your data? Try nesting each field call in a NULL replacement

  3. SSRS Divide by Zero Error

    My problem occurs with company_2 in period 202010. The expression doesn't seem to be filtering the 0 value in num_costs but it catches the prior

  4. SQL Server Reporting Services (SSRS)

    If you use the IIF statement to solve your divide by zero errors, you will most likely find that you still get divide by zero errors.

  5. SSRS Report Builder Part 7.3

    By Andrew Gouldhttps://www.wiseowl.co.uk - This video shows a couple of errors related to divide by zero errors in Report Builder and a

  6. SQL Server Reporting Services: How to Solve Divide by Zero Errors?

    you thought you wrote an if condition to handle “divide by zero” errors in SSRS but still get the run time error? Example. my expression is:.

  7. How to Avoid Divide by Zero in Custom Code Function Calls in SQL

    Here is a function build in the Custom Code section of the SQL Server Reporting Services report. Although there is an IIF conditional statement and checks

  8. reporting-services Tutorial => Using IIF to Screen for Division by

    SSRS does not short circuit IIF arguments. Therefore, using a single IIF function to screen for division by zero will have no effect and give an #ERROR

  9. Avoid Divide By Zero Error on SSRS

    SSRS functions (as all functions) doesn't like number divided by zero. But, SSRS function behaves weird when they meet an expression that can lead to divide

  10. SSRS: Checking for Divide By Zero Using Custom Code

    I soon realized that this does not resolve the issue. It appears that all parameters in the IIF function are evaluated regardless if the

  11. Divide by Zero error in SSRS reports

    Divide by Zero error in SSRS reports · This is a common error when we divide one field's value with another fields value or if second field