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.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
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.

=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?!
- reporting-services
- ssrs-tablix
- ssrs-expression

- You mentioned that there are nulls in your data? Try nesting each field call in a NULL replacement function. For example, I would the format IIF(Fields!PY_Dollars.Value = Nothing, 0, Fields!PY_Dollars.Value = Nothing) for each Fields!PY_Dollars.Value in the current formula. Better yet, handle the nulls in the source query instead. – Eric Hauenstein Oct 4, 2013 at 19:59
- The condition in your IIF statement is not checking for zero denominator (you are checking for zero in CY , not PY value). Instead, try: =IIF(Sum(Fields!PY_Dollars.Value)=0, 0, (Sum(Fields!CY_Dollars.Value) - Sum(Fields!PY_Dollars.Value))/(Sum(Fields!PY_Dollars.Value))) – rpyzh Feb 14, 2014 at 3:23
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:
- can we use Code.Divider() custom function in SQL or MDX within dataset ? Silly but I want something like this to avoid multiline IIF expressions in my huge MDX :( – Aditya May 29, 2014 at 13:45
- 1 This function can only be used in the report design surface, not in a SQL or MDX query. There are a number of approaches for handling divide-by-zero calculations in MDX, e.g. bidn.com/blogs/dustinryan/ssis/465/… , but if you have SQL Server 2012 or later you can use the new Divide() function which does a similar job to the above code. – Nathan Griffiths Jun 3, 2014 at 0:41
- 1 dont you have to define a return type? Is it not necessary? – Emil Jan 14, 2015 at 9:03
- 5 I wish I could upvote this like 1000 times. Thanks man, perfect solution. – LittleTreeX Mar 10, 2015 at 21:49
- 1 So... if anyone has to refactor their shared divide code out, this is an inline method that actually works sqldusty.com/2011/08/01/… . Basically IIF(denominator=0,0,Numerator) / IIF(Denominator=0,1,Denominator) – Nick.McDermaid May 12, 2021 at 4:24
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.

- I understand the logic and it should work but SSRS doens't calculate it correctly. I still get the error with this. – d90 Oct 8, 2013 at 17:19
- 2 +1. Here is a post on using double iif statements ntsblog.homedev.com.au/index.php/2010/03/12/… – Bobby Oct 8, 2014 at 8:13
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.
Why not just express the values as DOUBLE? This avoids the multiple IIF functions? It should have better performance too.
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 .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Are there tables of wastage rates for different fruit and veg?
- Example of trickiness of finite lattice representation problem?
- Why do many companies reject expired SSL certificates as bugs in bug bounties?
- "Is" or "are" for two uncountable words?
- Question about Nyquist sampling - filtering of high image copies
- Will DL360 Gen 8 servers fit in rails designed for DL360 Gen 7 servers?
- Recovering from a blunder I made while emailing a professor
- Who owns code in a GitHub organization?
- Why Chandrasekhar in 1931 used 2.5 for molecular weight?
- A plastic tab/tag stuck out of the GE dryer drum gap. Does anyone know what it is, if it is a part of the dryer, and if so how I can fix it?
- Difference between "select-editor" and "update-alternatives --config editor"
- Why did Windows 3.0 fail in Japan?
- How or would these mechanical wings work?
- Isolate page to turn off header
- Does melting sea ices rises global sea level?
- Conjugation of the Auxiliary Verb 得る When it's Read as うる
- Copyright issues when journal is defunct
- Is there a single-word adjective for "having exceptionally strong moral principles"?
- Should I put my dog down to help the homeless?
- Rolling cube on an infinite chessboard
- In general, in a string of multiplication is it better to multiply the big numbers or the small numbers first?
- How can I check before my flight that the cloud separation requirements in VFR flight rules are met?
- Tips for golfing in SVG
- Follow Up: struct sockaddr storage initialization by network format-string
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?

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
- Search for: Search

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.. 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. 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 .8 thoughts on “ SQL Server Reporting Services (SSRS) – IIF statement divide by zero error ”
Leave a Reply Cancel reply

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]

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]

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:
- Click to share on LinkedIn (Opens in new window)
- Click to share on Reddit (Opens in new window)
- Click to share on Twitter (Opens in new window)
- Click to share on Facebook (Opens in new window)
- Click to email a link to a friend (Opens in new window)
- Click to share on WhatsApp (Opens in new window)
- Click to share on Pinterest (Opens in new window)
- Click to share on Skype (Opens in new window)
- Click to share on Pocket (Opens in new window)
- Click to share on Telegram (Opens in new window)
- Click to share on Tumblr (Opens in new window)
- Click to print (Opens in new window)
3 thoughts on “ SQL Server Reporting Services: How to Solve Divide by Zero Errors? ”
Thanks. it worked.
- December 14, 2015 at 3:24 am
That’s great! I am glad this was useful.
- February 29, 2016 at 4:38 pm
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?
- January 20, 2022 at 11:43 pm
What do you think? Leave a comment below. Cancel reply
- SAP HANA ABAP
- Data Virtualization
- ASP.NET Visual Studio
- Purble Place
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.
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
- Getting started with reporting-services
- Check for NULL or Blank
- IF expression
- AND / OR IF condition
- If points field value is greater than 10 then display good else average
- Using IIF to Screen for Division by Zero
- Switch Expression
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.

- Advertise with us
- Privacy Policy
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

כתיבת תגובה
האימייל לא יוצג באתר. שדות החובה מסומנים *
התגובה שלך *
שמור בדפדפן זה את השם, האימייל והאתר שלי לפעם הבאה שאגיב.
Recent Posts
- מחשב הולך ומחשב בא – חיפוש Windows 10 לא פועל
- מכונות לומדות / הרצאה של יובל מזור, מיקרוסופט
- Aggregate function עם תנאי על אקסל / MaxIF
- חוויות מכנס מיקרוסופט AZURE
- עיבוד נתונים על גבי אקסל 2016
- הרשמה הצליחה
- שירותים מקצועיים
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.

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.

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.

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 ...
- Filtered Index in SQL server for Query optimization Filtered Index in SQL Server 2008 for Quey optimization SQL Server 2008 introduces an enhancement to the way the indexes are created ...
- Differences between CTE and View Differences between CTE and View CTE: CTE stands for Common Table expressions can be thought of as a temporary result set that is de...
- Format Date in SSIS MM-DD-YYYY or MM/DD/YYYY DD-MM-YYYY or DD/MM/YYYY Format Date in SSIS MM-DD-YYYY or MM/DD/YYYY DD-MM-YYYY or DD/MM/YYYY Date Format MM-DD-YYYY: RIGHT("0" + (DT_STR,4,1252...

IMAGES
VIDEO
COMMENTS
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
SSRS Expression Divide by Zero Error · You mentioned that there are nulls in your data? Try nesting each field call in a NULL replacement
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
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.
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
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:.
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
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
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
I soon realized that this does not resolve the issue. It appears that all parameters in the IIF function are evaluated regardless if the
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