Handle divide by zero exception in this SSRS rdlc expression - sql

The following code is showing result as Nan% if values are zero:
=FORMAT(((Sum(IIF(Fields!flag.Value=1,CINT(Fields!area1.Value),0)))
/ (Sum(IIF(Fields!flag.Value=1,CINT(Fields!UnitArea.Value),0))) *100),"N") + "%"

The simplest way to avoid the divide by zero error here is to not create it in the first place! If you replace the 0 as second return value in the divisor Iif expression with a 1, then the problem goes away.
That said I think your whole expression could do with simplifying somewhat. If I read it correctly you want to determine the proportion of area1 within UnitArea but only when the value of flag is 1. The expression could be thus written:
=Format(
Iif(
Fields!flag.Value = 1,
CInt(Fields!area1.Value) / CInt(Fields!UnitArea.Value),
Nothing
),
"Percent"
)
Note that I've dropped the multiplier and instead used the Format function to return the result of the division as a percentage (you could also simply further by removing the Format function entirely and handling the formatting in the designer).
You don't have to layout the expression with indentation as I have, but the expression builder ignores the whitespace and it does make larger expressions easier to read, so I think its a good habit to get into.

Related

How can I set a minimal amount of numbers after the decimal dot (0.9=>0.90)

I'm using google bigquery, and a column has values I want to round. If I do, and the rounded value ends in a zero, the zero is not displayed.
I've tried the function FORMAT, which apparently has some .number function, but I have no idea how to use it. Whenever I include any 2 things separated by a comma inside its brackets, it complains that it only takes 1 value.
You would use FORMAT() with the precision specifier. For four decimal places always -- including zeros:
select format('%.4f', 1.23)
If the BQ documentation does not answer your questions, I find that that the function seems to be inspired by the classic C printf()/sprintf() functions.
Unaware if in BigQuery (haven't used it ever) there is a better way I guess this will fix your problem since I just tried it in their console.
Cast your float to a string and then check if your last digit is a 0. In case it's not add it:
SELECT case when RIGHT(cast(0.9 as string), 1) <> '0' then cast(0.9 as string)+'0' else cast(0.9 as string) end as FormattedNumber

how to convert this String to Decimal

i have this String '5666,232343' and i want to convert it to Decimal, i use cast('5666,232343' as decimal(7,5)) but it returns NULL value.
Do you know why it doesn't work with CAST
Zorkolot is right. The current precision and scale that you've used is not sufficient for the value you've provided.
If you're using SQL Server 2012 or higher and you want to keep the comma in the value, then you can use the TRY_PARSE function and set a culture. It will return NULL if it encounters an error instead of not completing the statement and returning red text. This also allows you to add basic error handling to the statement, if you wanted, by getting failed conversions to return the value of zero. For example:
This is your original query (which is currently erroring) with my error handling fix:
select coalesce(try_parse('5666,232343' as decimal(7,5) using 'en-GB'),'0') as [DecimalValue]
This is the same thing as above but I've amended the decimal precision and scale so that the value is successfully converted:
select coalesce(try_parse('5666,232343' as decimal(16,6) using 'en-GB'),'0') as [DecimalValue]
This should prevent you having to perform a REPLACE either manually or by using the SQL function.
You need to cast to a decimal that can hold the value of 5666.232343.
DECIMAL(7,5) allows numbers in this format: ##.#####. The biggest number you can have then is 99.99999. You also need to take the comma out and replace it with a period:
SELECT CAST('5666.232343' as decimal(16,6)) AS [DecimalValue]
The problem is probably the comma. In some databases, some of the functions are not as internationally-sensitive as (I think) they should be. So try:
cast(replace('5666,232343', ',', '.') as decimal(7, 5))

SSRS expression causing error

I have the following expression in SSRS:-
=IIf(IsNothing(Fields!Hours.Value), 0, Sum(Fields!Hours.Value) / Sum(Fields!ReportingHours.Value))
The expression appears as #Error. I removed the division part of the equation, leaving just this:
=IIf(IsNothing(Fields!Hours.Value), 0, Sum(Fields!Hours.Value))
Then the correct numbers appear. If I perform an addition operation, the calculation also errors out. It seems that it does not like something about performing mathematical operations when using the Sum() function. If I do simple division without the Sum, as in this expression:
=IIf(IsNothing(Fields!Hours.Value), 0, Fields!Hours.Value / Fields!ReportingHours.Value)
Then numbers show up fine. It is only when I have the Sum() function on the expression that causes an error. Any ideas as to how to fix this?
Try the following expression:-
=IIf(IsNothing(sum(Fields!Hours.Value)), 0, Sum(Fields!Hours.Value) / Sum(Fields!ReportingHours.Value)
EDIT
I have edited my previous post.

divide by zero/null workaround in SSRS 2008 report

I have a report with a field whose value was the expression:
Fields!TotalPrice.Value/Fields!TotalSlots.Value
Although sometimes TotalSlots was blank and thus I was getting a divide by zero runtime error. So I changed the expression to this:
=IIF(Fields!TotalSlots.Value > 0, Fields!TotalPrice.Value/Fields!TotalSlots.Value,"unknown")
but I'm still getting a divide by zero error. How do I work around this zero divisor issue.
Jamie F's answer is correct. As a tip, you can add a function to your report code to make the division a bit easier to implement in multiple cells, e.g.
Public Function Divider (ByVal Dividend As Double, ByVal Divisor As Double)
If IsNothing(Divisor) Or Divisor = 0
Return 0
Else
Return Dividend/Divisor
End If
End Function
You can then call this in a cell like so:
=Code.Divider(Fields!FieldA.Value, Fields!FieldB.Value)
The VB IIF evaluates all arguments, so it will throw an error if any argument throws an error:
Your formula can be written as:
=IIF(Fields!TotalSlots.Value > 0,
Fields!TotalPrice.Value /
IIF(Fields!TotalSlots.Value > 0,
Fields!TotalSlots.Value,
1 ),
"unknown")
Then even when TotalSlots is zero, the formula still won't encounter a division problem.
I don't think your error is on the calculation. First of all, SSRS deals automatically with this situation. See my third column. And the forth shows your expression:
Your problem is probably somewhere else
This only seems to happens when the division is one of the results of an IIF, not if you just write a formula to divide one by the other, e.g.
=IIF(thing=1,10/0,0)
Before it has evaluated thing, it has already tried to calculate both results, causing an error. You can't use IIF in this way to protect from zero, you have to put the IIF on the bottom line of the division, e.g.
=IIF(thing=1, 10/IIF(divisor=0,-99999999999,divisor),0)
This is not satisfactory, since we've introcudes a weird small non zero number as the result, but it may be ok if you just want a non-error.
Technically, the #error is the correct answer.
Function IIF(arg1, arg2, arg3) always calculates all arguments, before returns a result, so your 2nd argument Fields!TotalPrice.Value/Fields!TotalSlots.Value can return #Error.
Try to use IF(arg1, arg2, arg3) function instead IIF.
=IF(Fields!TotalSlots.Value > 0,
Fields!TotalPrice.Value/Fields!TotalSlots.Value,
"unknown")

ISNUMERIC('07213E71') = True?

SQL is detecting that the following string ISNUMERIC:
'07213E71'
I believe this is because the 'E' is being classed as a mathmatical symbol.
However, I need to ensure that only values which are whole integers are returned as True.
How can I do this?
07213E71 is a floating number 7213 with 71 zeros
You can use this ISNUMERIC(myValue + '.0e0') to test for whole integers. Slightly cryptic but works.
Another test is the double negative myValue NOT LIKE '%[^0-9]%' which allows only digits 0 to 9.
ISNUMERIC has other issues in that these all return 1: +, -,
To nitpick: This is a whole integer. It is equivalent to 7213 * 10 ^ 71.
In the documentation it says
ISNUMERIC returns 1 when the input expression evaluates to a valid integer, floating point number, money or decimal type; otherwise it returns 0. A return value of 1 guarantees that expression can be converted to one of these numeric types.
Your number is also float (with exponential notation), therefore the only way to have ISINTEGER is to define it yourself on SQL. Read the following link.
http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html
Extras:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=59049
http://www.tek-tips.com/faqs.cfm?fid=6423
I have encountered the same problem. IsNumeric accepts "$, €, +, -, etc" as valid inputs and Convert function throws errors because of this.
Using "LIKE" SQL statement fixed my problem. I hope it'll help the others
SELECT UnitCode, UnitGUID, Convert(int, UnitCode) AS IntUnitCode
FROM [NG_Data].[NG].[T_GLB_Unit]
WHERE ISNULL(UnitType,'') <>'Department'
AND UnitCode NOT LIKE '%[^0-9]%'
ORDER BY IntUnitCode
PS: don't blame me for using "UnitCode" as nvarchar :) It is an old project :)
You have to ensure it out of the call to the database, whatever the language you work with, and then pass the value to the query. Probably the SQL is understanding that value as a string.