Dynamic WHERE clause in MS Access - ms-access

I am trying to get the following result in a query.
SELECT * FROM rosterTbl
WHERE (IIF( ISNULL([Forms]![ReportsGUI]![cmbCounsellor]), rosterTbl.CounsellorID<>null,rosterTbl.CounsellorID=[Forms]![ReportsGUI]![cmbCounsellor]
I know the above query is incorrect but I need the result: If cmbCounsellor is Null Then all counsellors Else specific counsellor.

Perhaps something like this will work:
="SELECT * FROM rosterTbl WHERE CounsellorID " & IIf(IsNull([Forms]![ReportsGUI]![cmbCounsellor], "IS NOT NULL", "= " & [Forms]![ReportsGUI]![cmbCounsellor])
edit re: comments
In this particular case the WHERE condition will be used to control the records to be included in a report, so the compete SELECT statement is not really required. Instead, the "WHERE" clause can be passed to the report via the WhereCondition argument of DoCmd.OpenReport, something like this:
DoCmd.OpenReport "MyReport", acViewPreview, , "CounsellorID " & IIf(IsNull([Forms]![ReportsGUI]![cmbCounsellor], "IS NOT NULL", "= " & [Forms]![ReportsGUI]![cmbCounsellor])

This is the way to do this within query:
SELECT * from rosterTbl
WHERE [Forms]![ReportsGUI]![cmbCounsellor] IS NULL
OR
rosterTbl.CounsellorID
= ([Forms]![ReportsGUI]![cmbCounsellor])

Related

Enter parameter value but I've already included one in the query

I've got a SQL query in my VB6 project that is performing a three-way INNER JOIN in an Ms-Access database.
The VB6 query is:
SQL = "SELECT popsLines.stockCode, popsLines.orderNumber, popsOrders.dateOrdered, popsReceipts.dateReceived, popsReceipts.reference" & _
" FROM (popsOrders INNER JOIN popsLines ON popsOrders.orderNumber = popsLines.orderNumber)" & _
" INNER JOIN popsReceipts ON popsOrders.orderNumber = popsReceipts.orderNumber" & _
" WHERE (([WHERE popsLines].[stockCode]=" & sqlString(m_sStockCode) & "));"
This wasn't working, it returned an error saying
No value given for one or more required parameters
So then next thing I did was copy the value in the SQL variable and paste it into an Access query, with the value of the m_sStockCode parameter.
SELECT popsLines.stockCode, popsLines.orderNumber, popsOrders.dateOrdered, popsReceipts.dateReceived, popsReceipts.reference
FROM (popsOrders INNER JOIN popsLines ON popsOrders.orderNumber = popsLines.orderNumber)
INNER JOIN popsReceipts ON popsOrders.orderNumber = popsReceipts.orderNumber WHERE (([WHERE popsLines].[stockCode]="010010003"));
When executing this, it said
Enter Parameter Value: WHERE popsLines.StockCode
Why isn't it accepting the query as it is?
I've also tried changing there WHEREclause to
(( WHERE [popsLines].[stockCode]="010010003"));
but got
Syntax error (missing operator) in query expression '((WHERE [popsLines].[stockCode]="010010003"))'
The last part - your WHERE clause - is garbled. It should read:
.. WHERE ([popsLines].[stockCode]='010010003');

"Data type mismatch in criteria expression"

I have tried to select all records from a table from date1 to date2, Example Jun 28, 2014 to Jan 05, 2015, for display. Basically, sort out selected records based on date criteria. Big thanks if anyone could point out my mistake.
What I tried to do here is allowed user to select specific dates from calendar to view the records
I have gone through all answers, but still couldn't find similar solution to mine. I think, there may be some error in my syntax.
sqlDateRangeSearch = "Select * from BatteryDataTable where ((BatteryDateChanged) <= ""*" & Me.FromDTPicker.Value & "*"")" & " and ((BatteryDateChanged) <= " & """*" & Me.ToDTPicker.Value & "*""));"
Me.RecordSource = sqlDateRangeSearch
I noticed you have wildcard characters in the search criteria for the query. If using dates, you'll want to avoid those. Also, you don't need quotes for dates in access queries. If you're dynamically creating SQL I'd use something like:
sqlDateRangeSearch = "Select * from BatteryDataTable where (BatteryDateChanged <= #" & Me.FromDTPicker.Value & "#)" & " and (BatteryDateChanged <= #" & Me.ToDTPicker.Value & "#));"
Just a side note, your comparison operators are the same. I think you want it to say something like (remember the "#" symbols):
...WHERE (Field1 >= #Date1# AND Field1 < #Date2#);
Hope that helps!

Change SSS Report Condition based on report Parameter

I spent some time looking around at other questions on the board, but didn't find anything similar so here it goes:
I have a report that runs up against the limits of CRM 2011 online in regards to the max number of characters in a Fetch Query. I would like to have a drop box that has an option for "All Contacts" or "Select up to Five Contacts" to avoid that issue.
What I would like to do is remove the condition from the Fetch statement if the "All Contacts" option is selected, and include the condition only if the select up to five is chosen.
How would I go about doing this?
Let me know if you have any further questions.
Nick
You can build your SQL using custom code because the SQL itself can be a string expression that you build manually. Let's say your SQL looks like this at the moment:
SELECT ThisField, ThatField
FROM Contacts
WHERE ContactId IN #Contacts
Let's change that to a string expression that builds the SQL:
="SELECT ThisField, ThatField "
& "FROM Contacts "
& "WHERE ContactId IN #Contacts "
Now we need to pull the #Contacts parameter apart and only select by ContactId when there are five or less contacts selected:
Function ContactsSQL(ByVal parameter As Parameter) AS String
Dim Result As String
Result = ""
If parameter.IsMultiValue Then
If parameter.Count <= 5 Then
Result = "WHERE ContactId IN ("
For i As integer = 0 To parameter.Count-1
Result = Result + CStr(parameter.Value(i)) + ", "
Next
Result = Left(Result, Result.Length - 2) + ") "
End If
End If
Return Result
End Function
This function builds the SQL WHERE clause to select the contacts only if five or less have been selected, otherwise it passes back an empty string. Now we use this function in our SQL expression:
="SELECT ThisField, ThatField "
& "FROM Contacts "
& Code.ContactsSQL(Parameters!Contacts)
Note that you are passing the Contacts parameter object here, not the Value property. We access the Value property in the custom code function.

Multifield Search, Incorporating age range criteria?

I'm trying to add a multifield search into a form, but I ran into a jam. I have it figured out for my 4 text fields. Here's the code I use utilizing wildcards so that it searches all records if it's left blank
Like "*" & [Forms]![Patient Tracking]![FNSearch] & "*"
But now, I'm trying to add an age range feature. It's stored as a simple numerical field. I just need to create a way where you can enter an age range (lowest in textbox named minage, highest in maxage textbox) and have it also be ignored if left blank.
Any idea how to create this criteria?
this is the entire code of the query in sql:
SELECT [Patient Tracking].[First Name], [Patient Tracking].[Last Name], [Patient Tracking].City, [Patient Tracking].Sex, [Patient Tracking].Age
FROM [Patient Tracking]
WHERE ((([Patient Tracking].[First Name]) Like "*" & Forms![Patient Tracking]!FNSearch & "*") And (([Patient Tracking].[Last Name]) Like "*" & Forms![Patient Tracking]!lnsearch & "*") And (([Patient Tracking].City) Like "*" & Forms![Patient Tracking]!citysearch & "*") And (([Patient Tracking].Sex) Like "*" & Forms![Patient Tracking]!sexsearch & "*"))
I found a simpler method using the NZ Function,
Between Nz([Forms]![Patient Tracking]![minage],0) And Nz([Forms]![Patient Tracking]![maxage],10000) Or Is Null
thanks for the help

SQL Select statement wont return char fields only numeric fields

I have been racking my brain over this all day today.
I have the following ASP code that uses a Request.Querystring input from a dropdown box
to launch a select statement. The querystrinch does show in the ?= URL but will only work on
columns in the Microsoft SQL DB that are numeric. I cant lookup names or simple 3 character fields.
CODE:
If Request.QueryString("m") > 0 Then
filterID = Request.QueryString("m")
filterColmn = "imDegree"
Else filterID = 0
End If
If filterID > 0 Then
SQlQuery = "SELECT * FROM v_InternImport WHERE iID IN (SELECT iID FROM v_InternImport WHERE " & filterColmn & " = " & filterID & ")"
End If
End If
I understand that this select statement as a sub select stament in it but I cant even get a staight reuturn from my DB. The select statement references the same view that populates the main asp page that loads before and the shows fine?
When you pass a string to SQL Server, you need to surround it with single quotes.
When you pass a number, you don't use the quotes.
So, when you say (summarizing)
SELECT * FROM table WHERE filterColumn = filterID
you should be sending a number.
To match a string:
SELECT * FROM table WHERE filterColumn = 'filterID'
This assumes that you have solved any other problems mentioned by the commenters about whether you even have a value in the filterID variable. I heartly concur with the recommendation to use parameterized queries.
Edit: The single quotes go inside the double quotes.
SQlQuery = "SELECT * FROM v_InternImport
WHERE iID IN (SELECT iID FROM v_InternImport
WHERE " & filterColmn & " = '" & filterID & "')"