Syntax In Access 2010 IIF Query - mysql

I am a beginning user of Access, and am trying to build a query inside of a form.
I am working on my first IIF query, and am having trouble getting the desired behavior.
I am trying to pull results based on 4 entries, called [band], [band2], [band3] and [band4].
Here is where I'm at:
Like IIf(IsNull([forms]![financial_filter]![band]),"*",[forms]![financial_filter]![band]) Or Like [forms]![financial_filter]![band2] Or Like [forms]![financial_filter]![band3] Or Like [forms]![financial_filter]![band4]
This means that if the [band] field is empty, it will pull all results for all bands. But if the [band] and/or [band2-4] fields are filled in, it will pull results from only those fields. This is all working.
BUT, if a user leaves the [band] field empty and only enters something in the [band 2-4] fields, all results show up, not just those related to the data in the [band 2-4] fields. Please advise how to modify my query so that if a user chooses one or more bands but does not put anything into the [band] field, only the selected results will populate.
Thanks!
Mike

IIF has nothing to do with Query.
The IIF statement is a shortcut for a IF .. THEN .. ELSE .. END IF statement.
MyResult =IIF (Condition, Make1, Make2) means
IF Condition THEN
MyResult=Make1
ELSE
MyResult= Make2
END IF
You can nest IIF statements, but the result will be difficult to read and also to maintain.
So, in your case I would suggest to write a couple of lines with your business logic (IF THEN ELSE END IF) or (IF THEN ELSEIF ... END IF) in the OnCurrent Event of your form, improving future maintenance and readability of your code.

Related

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] = "*"

query to filter on specific data or no filter if blank

I have a query which filters records based on dates (start date and end date)selected in a previous form. I want the query to filter the specific date range, or output all records if the fields are left blank.
I am unfamiliar with SQL. is there a way to add an if-then statement?
I can use vba if necessary, but would like to use the Access GUI if it is possible.
If you have a parameter, used in WHERE clause (Criteria in query builder) and you want to show all records if parameter is empty, just add this parameter as new column and OR condition where indicate Is Null or, better add a column with expression Nz([MyParam],"") and in Condition area inORrow add""`. Unfortunately in query builder this construction may be quite complicated if you have few parameters, in SQL it looks much simpler, for instance in your case it will be something like this:
WHERE (MyDate >= [paramDateStart] and MyDate <= [paramDateEnd])
OR (Nz([paramDateStart],"")="" AND Nz([paramDateEnd],"") = "")
Sometimes simpler edit SQL and then switch to Design view
You can use these criteria for StartDate and EndDate respectively to compare them to themselves in case one (or both) of the search fields on the form is empty (Null):
>=Nz([Forms]![YourForm]![FromDate], [StartDate])
<=Nz([Forms]![YourForm]![ToDate], [EndDate])

Hiding Rows with Blank Fields in Access Subreport

I have a subreport, ExpenSubrpt, in Access 2010 that’s basically a table with two columns: YearNo, and Amount. These values are taken from another table, Expenditures. Long story short, some records in my database have rows with no YearNo. What I want to do is to hide the rows that don’t have a YearNo, ie. YearNo is blank but there is something in Amount. For example:
YearNo Amount
20
1 50
I want the first row to not be visible. I’ve tried putting
"[YearNo] <> " " AND [YearNo] IS NOT NULL"
into the Data -> Filter tab, but it gives me a syntax error (missing operator). When I removed the space, the error goes away but it doesn't filter, either. I've also tried calling a query by using the OnLoad event.
Private Sub Report_Load()
DoCmd.OpenQuery "Expenditures Query"
End Sub
Query:
SELECT Expenditures.YearNo, Expenditures.Amount
FROM Expenditures
WHERE (((Expenditures.YearNo) Is Not Null));
However, this doesn't work either. I’m not really sure what to do from here, or if there’s a better way to filter this form. Any assistance would be greatly appreciated.
You might want to change your query to have the "Not" before the field name, like this...
SELECT Expenditures.YearNo, Expenditures.Amount
FROM Expenditures
WHERE ((Not(Expenditures.YearNo) Is Null));

Access IIf statement retrieving a value using a Check Box

I am attempting to have a single List Box pull up two possible values based on whether or not a Check Box is filled. The Row Source I have for the List Box is:
IIf([Forms]![frmPDPRate]![chkTrue], [qryPDPRate]![Initial], [qryPDPRate]![Renewal])
The specifics are that I'm trying to pull a rate, either Initial or Renewal, based on if [chkTrue] is true or false.
Another note: The query that the list box should be pulling from has been paired down to one row based on cascading combo boxes. So there is only one possible choice per column in the query.
EDIT:
I think I'm going about this all wrong but I don't know how to get it to do what I want at this point.
Yawar, nothing is happening when I run the form but that makes sense as I can't force the rowsource to choose between two possibilities.
I think you need the following code in VBA:
Private Sub chkTrue_AfterUpdate()
If chkTrue =TRUE then
listbox.RowSource = "SELECT Initial FROM qryPDRRate"
Else
listbox.RowSource = "SELECT Renewal FROM qryPDRRate"
End If
End Sub
I was able to use the Query Builder in the RowSource Property using an IIf statement. The RowSource Data Looks as such.
SELECT IIf([Forms]![frmPDPRate]![chkTrue],[qryPDPRate]![Initial],[qryPDPRate]![Renewal]) AS Rate FROM qryPDPRate;

Efficient use of calculations in MS Access

This is the kind of thing I feel I should already know, but don't...
In MS Access, if a query consists of n calculated fields (say calc_1, calc_2, .... calc_n) but I only want to use a subset of them in a particular form or report - say calc_x, calc_y and calc_z - would Access calculate all n calculations when running SELECT calc_x, calc_y, calc_z FROM myquery and then return the ones I want, or would it be smart enough to only calculate calc_x, calc_y and calc_z?
In my case I'm using Access 2003 but presumably the answer is the same for all versions.
Access is smart and don't calculate not-visible fields.
Tried with Access 2003
Like #David, I did not believe #Andreas's answer at first. So I tested it myself as follows. I created the following function:
Function Watch(Val, Optional CalledFrom As String = "")
Debug.Print Val, CalledFrom
Watch = Val
End Function
Then I created a table named "Dummy" with a single field named "ID". I created a form and used the following as the form's RecordSource:
SELECT Watch([ID],"ShowInForm") AS ShowInForm,
Watch([ID],"HideFromForm") AS HideFromForm
FROM Dummy;
I added a single textbox control with a ControlSource of ShowInForm.
I then opened the form and got this in the immediate window:
1 ShowInForm
1 ShowInForm
1 ShowInForm
I then went back to the RecordSource and previewed it in Datasheet view and got this:
1 ShowInForm
1 HideFromForm
I'm not sure why the "ShowInForm" expression is evaluated three times in the form, but it seems pretty clear that the unused field, "HideFromForm", does not get evaluated.
To address #HansUp's comment, I went back and saved a query named "Qry":
SELECT Watch([ID],"ShowInForm") AS ShowInForm,
Watch([ID],"HideFromForm") AS HideFromForm
FROM Dummy;
Then changed the form RecordSource to:
Select ShowInForm FROM Qry
This produced the same result as before when I opened the form (ie, 3 lines of 1 ShowInForm). Interestingly, when I opened the RecordSource in datasheet view I got this:
1 ShowInForm
1 ShowInForm
In other words, it evaluated the ShowInForm field twice. Presumably, once in "Qry" and again in the RecordSource query.
The end result is still a confirmation of #Andreas's answer.
If you include the calculated fields in the SELECT clause of your report or form's recordsource, it will calculate them for each row AS IT IS RETRIEVED.
If you leave them out of the SELECT and include the calculations only in the ControlSource properties of controls on your report/form, then what you say is true.
Also, if you do any sorting/grouping on the calculations or put criteria on them, all rows will be calculated.
Thus, in this recordsource:
SELECT Field1/Field2 As Ratio1, Field3/Field4 As Ratio2, FIeld1, Field2, Field3, Field4
FROM MyTable;
...for each row that is retrieved, both calculations will be executed regardless of whether or not the result is used in the form or report.
If you want to delay calculations to the last possible moment, do NOT include them in the SQL recordsource, but just use them as the ControlSources of the controls that are displaying the calculations. However, this has the downside that you'll see the calculations painting onscreen in many cases.
EDIT:
It seems this may not be correct, but I feel there's something going on here that is not completely explained by #mwolfe02's answer. I'll just leave this here for further discussion.
I put calculations like this on the server side.. computed columns are awesome.
I think that Access finally got this feature in 2007, I don't know how people ever survived without it.