In Access, is the "falsepart" of the IIf Function required? - ms-access

While converting some Access queries to T-SQL, I came across the Access function IIf. I read the documentation here and understand it takes 3 parameters: the expression, the if true, and the if false. What I have yet to find is if the "false" param is required? And if a false is not provided, what is the behavior?
UPDATE:
When this question was asked, I did not know if the query worked with only 2 parameters (b/c I can not run the query in Access). I did, however, suspect it might work (with only 2 params) b/c a few queries I am converting (to T-SQL) have nested IIF's and the last IIF has only 2 params.

It's IIf, not IFF. All arguments are required in VBA and textbox expressions and both must be calculatable (no error result such as DivBy0) because both parts will be calculated - if either errors, the entire expression errors. The IIf() in Access query works differently - 'falsepart' calculates only if 'truepart' fails and if 'falsepart' is not provided, expression returns Null if 'truepart' fails.
Try some expressions and see what happens. One for testing: IIf(1=2,"T").

Addendum to June7's excellent answer:
Here are two simple queries that work in Access SQL:
SELECT IIf(1=1, "yes")
(returns "yes")
SELECT IsNull(IIf(1=2, "yes"))
(returns -1 aka True) - so if you omit falsepart, IIf() returns indeed NULL if expr doesn't evaluate to True.

Yes, it's required, it's actually like an if else statement.
i.e an action occurs if the condition is fulfilled, and another action occurs if condition is not fulfilled

Related

How to get around '#Error' when a function in MS Report Builder is evaluating a null value?

I hope my title is clear enough. I'm working in MS Report Builder, using a function that applies a regular expression to a queried value in order to get back a certain substring. The regex works fine, so I'll demonstrate a simpler version here to make this less wordy. Here's the gist of my equation:
=IIF(Len(Fields!CourtLocation.Value) < 1, "none",System.Text.RegularExpressions.Regex.Match(Fields!CourtLocation.Value, "(?:[A-Z]{2,4})").Value))
The main purpose is to get that substring, but I added the IIF so that on those occasions when the CourtLocation.Value is empty (I tried Is Nothing in my expression as well), the function returns "none" rather than "#Error"
I've been looking around for a solution, but nothing has worked; it seems like most other people who talk about this are using a mathematical equation rather than trying to get a string. Can anyone help me get rid of that stupid "#Error" value?
You could try this (untested)
=System.Text.RegularExpressions.Regex.Match(
IIF(
Len(Fields!CourtLocation.Value) < 1,
"none",
Fields!CourtLocation.Value
)
, "(?:[A-Z]{2,4})"
).Value
This way the IIF is performed on the string that you want to pass to the regex function, so it always gets a valid value to process
Iif evaluates both sides, so you can nest two Iif statements to avoid the error.
Did you already read this one?
https://sqldusty.com/2011/08/01/ssrs-expression-iif-statement-divide-by-zero-error/
I'll copy the text into the answer if that solves it for you.

IIF query expression using Like "*" for the True condition

I have a database which tracks employee QA. I'd like to be able to search by a single Staff Member, a whole team, or a Unit. I have three controls that correspond to those fields and only one can ever have a value at once. In my quesry I'd like to have threee expressions that will limit my results by one of those three fields. I'm adding just one to start and I've hit a problem.
I found this https://www.acuitytraining.co.uk/microsoft-training-courses/access/if-statements/ which seems to do what I want. Here is the code I'm trying.
IIf(IsNull([Forms]![MainMenu]![btnManagersMenu].[Form]![cmbStaffSelect]),
[UserLogin] Like "*",[UserLogin]=[Forms]![MainMenu]![btnManagersMenu].
[Form]![cmbStaffSelect])
Which works fine if the control has a value. (condition is false) If the dropdown has no value (condition is true) I get zero results. I suspect the problem lies with the Like "*" on my UserLogin field. Here is my query wizard and the buildler wizard for the IIF expression
Can anyone see why I'm not getting any results for the dropdown control being empty. To my thinking this should give me an unfiltered list of results. I have double checked my data and there are 137 records that should appear if I'm not limited by the staff selection.
The short version of this is if cmbStaffSelect has a value I want my records limited by that value. If cmbStaffSelect is blank I want to get all records.
Keep in mind that the iif function will always evaluate both the then and else arguments, before returning the appropriate value depending on the value returned when evaluating the supplied test expression.
As such, if either the then or else arguments have the potential to error when evaluated (regardless of the result of the evaluation of the test expression), then the iif expression has the potential to error.
As an alternative, you could use the Nz function to achieve the same result:
[UserLogin] LIKE Nz([Forms]![MainMenu]![btnManagersMenu].[Form]![cmbStaffSelect],"*")
Perhaps your IsNull([Forms]![MainMenu]![btnManagersMenu].[Form]![cmbStaffSelect]) is always returning false because cmbStaffSelect might be equal to empty string?
Try something like this:
IIf(Trim([Forms]![MainMenu]![btnManagersMenu].[Form]![cmbStaffSelect] & "") = "",
[UserLogin] Like "*",[UserLogin]=[Forms]![MainMenu]![btnManagersMenu].
[Form]![cmbStaffSelect])
This checks to see if the cmbStaffSelect is "" ... if cmbStaffSelect is null - it converts it to "" by appending an "" to the null value.
I believe your hunch is exactly correct. If you want your query result to return the * symbol for the UserLogin field; then alter your IIF statement to be: [UserLogin] = "*"

SSRS PMT Function producing #ERROR

I am hoping someone can help me here. I am using the PMT function to calculate mortgage payments in SSRS. I am using the following Formula
=IIF(Note = "Present",-PMT(Rate/12,Term,Balance,0,DueDate.EndOfPeriod),Nothing))
The formula works perfectly when Note = Present. However on all other loans it is producing #ERROR. I don't understand why this is happening.
Is there some other error handling that needs to be done to simply leave the cell blank if the note is not present?
I'm not familiar with PMT but it could be that the values passed to PMT are invalid for loans where Note is not "Present". If this is the case then I would use a SWITCH statement instead. SWITCH will stop at the first expression that evaluates to True, whereas IIF evaluates all expressions, even the expression that does not get used!
try this..
=SWITCH(
Note <> "Present", Nothing,
True, -PMT(Rate/12,Term,Balance,0,DueDate.EndOfPeriod)
)
This way, if note is not "Present" then return nothing and only if it IS "Present" evaluate the PMT function and return its value. The True just acts like an else to save us writing Note = "Present" for the second condition
SSRS will always evaluate both sides of a conditional expression, no matter what the result of the first parameter boolean test. This means that
-PMT(Rate/12,Term,Balance,0,DueDate.EndOfPeriod)
must be a valid calculation for rows where Note <> "Present" as well or you will get an expressions error. I would suggest that probably some of the other fields aren't populated with appropriate "dummy" values in this scenario.
What is Nothing in your code?
=IF(Note = "Present",-PMT(Rate/12,Term,Balance,0,DueDate.EndOfPeriod),0))

Problem evaluating NULL in an IIF statement (Access)

Item in the recordset rstImportData("Flat Size") is = Null
With that, given the following statement:
IIF(IsNull(rstImportData("Flat Size")), Null, cstr(rstImportData("Flat Size")))
Result: Throws error 94: Invalid use of Null
If I change the statement by removing the type conversion upon a false comparison:
IIF(IsNull(rstImportData("Flat Size")), Null, 0)
Result: Null
It returns Null as it should have the first time. It appears that I cannot do a type conversion in an IIF if the value passed in should ever be null even if it passes an IIF test, it still attempts to evaluate it at both the true and false answer. The only reason I'm using IIF like this is because I have a 25 line comparison to compare data from an Import against a matching record in a database to see if I need to append the prior to history.
Any thoughts? The way data is imported there will be null dates and where the spreadsheet import is in a string format I must convert either side to the other to compare the values properly but if either side is null this exception occurs :(
EDIT
Example of why I was using IIF (and considering using a universal function)
If master("one") <> import("one") Or _
master("two") <> import("two") Or _
master("date") <> import("date") Or _ //import("date") comes from a spreadsheet, it comes in as string, CAN be a null value
master("qty") <> import("qty") Or _ //import("qty") comes from spreadsheet, comes in as a string can CAN be null
master("etc") <> import("etc") Then
....stuff....
End If
This code expands for roughly 20 columns to compare in the database. I would prefer to check as part of the statement. I can think of a bunch of solutions but they involve adding much more code. If that is the case power to it, however I'm not one to give in so easily.
Options I see are
Creating temp vars to do the work prior to comparing and using these new vars instead of the recordset
Creating an object to pass the record into to preformat and work with, though extra work would provide this functionality to each import type since there are different files with similar fields
I'm here for ideas, and I'm open to any interesting pieces that can be thrown my way as I get to decide how to do it I'm looking for the most reusable approach.
The simple expedient of changing the value to a string helps tremendously. The trick is that trimming a string which is NULL will get a null string. Which can then be operated on as if it wasn't a database null.
I frequently use the form:
CInt("0" & Trim(SomeVariant & " "))
To get a valid number without having to go through a bunch of hijinks. The null is a nonentity for this problem.
The behavior you described is the standard way IIf operates under VBA. This is part of what Access 2003 Help says about it:
"IIf always evaluates both truepart and falsepart, even though it returns only one of them. Because of this, you should watch for undesirable side effects. For example, if evaluating falsepart results in a division by zero error, an error occurs even if expr is True."
However, if you use an IIf statement in a query, evaluation short circuits after truepart when expr is True --- falsepart is not evaluated in that case. Unfortunately this information is not useful for you ... unless you can incorporate a query into your comparison.
I don't know of any other way to avoid your error with IIf. I would try appending the Excel data into a table whose structure matches that of the table you will compare against, thereby eliminating the need to do a string conversion at the same time you do the comparison.

Code not running when Field is NULL - SSRS 2005

I have a textbox in my SSRS 2005 report. The expresssion for this textbox is:
=IIF(IsDBNull(Fields!fOrgID), Code.SetMyVar("null"), Code.SetMyVar(Fields!fOrgID.Value))
I have also tried IsNothing(Fields!fOrgID) and a few other variations of checking for nulls.
I have modified the SetMyVar function for testing and it now looks like this:
Public Function SetMyVar (var as String)
MsgBox(var, VbOKCancel, "Test1")
If var Is Nothing Then
Return "NOTHING"
Else
MyVar = var
Return var
End If
End Function
I also have the public variable MyVar:
Public Shared Dim MyVar as String
When my database query returns data, this correctly evaluates, a messagebox is displayed with the value, the textbox gets set with the value, and the world is generally a happier place.
When my database query does not return a value though, I get the error:
The query returned no rows for the data set. The expression therefore
evaluates to null.
and the SetMyVar function never appears to be ran (you never get the messagebox popup). As expected, my emotions range from anger, sadness, and bitter hatred of SSRS.
I read something about SSRS evaluating both sides of an IF statement, so perhaps that is why I get the error (likely then on Code.SetMyVar(Fields!fOrgID.Value))... not sure how I get around that though.
Thoughts? Suggestions? Words of comfort?
From the sound of things, it seems likely that the issue is that SSRS is having a problem displaying zero records. I'd recommend one of the following:
1) Use a control that handles zero records appropriately (Tables do. I think Lists do as well).
2) Modify your query to return a single record with blank values if it would otherwise return zero records.
An answer to the original question:
=IIF(IsNothing(Fields!fOrgID),
Code.SetMyVar("null"),
Code.SetMyVar(IIF(IsNothing(Fields!fOrgID),"Foo",Fields!fOrgID.Value)))
The error was from both sides of IIF being evaluated. The extra IIF in the statement above will avoid Code.SetMyVar from ever being called with a null value.
I believe you're right about about Iif always evaluating both of its value arguments (at least, it does in Visual Basic). I'm not sure why you're getting this precise error (unless strings can't be assigned a value of DBNull?), but you almost certainly want to attack this problem with a different method.
The reason for this is that your current code will likely always call both set methods regardless of the conditional value.
Formula that worked for my SSRS 2008 reports.
=IIf(String.IsNullOrEmpty(Fields!NullableFieldwithPossibleBlankStrings.Value),"Yes","No")
I tried this too (also tried a version with IsNothing)...
=Code.SetField(IsDBNull(Fields!fOrgID))
And changed the function to be one that accepts a boolean. I figure this above function would always return a true or false, but in the event of a NULL, I again get "The query returned no rows for the data set. The expression therefore evaluates to null.".
I need to pass back to my code if the field is null or not (as this will let me know if the datasource is null or not).
Let me know if you can think of a better way because I cannot.