问题
I'm designing a search form to search my access database based on 4 text fields, Firstname, Surname, Phonenumber and Promo Code.
The queries look like:
Like "*" & [Forms]![SearchF]![txtFirstName] & "*"
Like "*" & [Forms]![SearchF]![txtSurnameName] & "*"
Like "*" & [Forms]![SearchF]![txtPhone] & "*"
Like "*" & [Forms]![SearchF]![txtPromo] & "*"
The search should return all records if all the fields are blank. When you enter some values in the text boxes, the results are narrowed down to matches.
It almost works fine, but problems occur when there is no value in certain fields. For instance, if someone doesn't have a promo code then their record will always be skipped over even if you leave it blank. I assume the access query doesn't like blank fields.
What's the easiest way to get around this?
回答1:
I think the text boxes may be a bit of a distraction here, because the issue is more basic. Consider this query ...
SELECT f.id, f.some_text
FROM tblFoo AS f
WHERE f.some_text Like "*";
It returns rows where some_text
contains any non-Null value, even an empty string. However it will not return rows where some_text
is Null.
The reason is that Null in a Like
comparison will never evaluate as True. Consider this example from the Immediate window ...
? "foo" Like "*"
True
? Null Like "*"
Null
For your Like
comparisons, I think you want the rows where the target field contains the text box text. But return all rows when the text box is Null. You can do that by combining those two conditions with OR
.
WHERE
[Promo Code] Like "*" & Forms!SearchF!txtPromo & "*"
OR
Forms!SearchF!txtPromo Is Null
When the text box is Null, the second part of the OR
is true for all rows, so all rows are returned.
When the text box is not Null, only those rows which satisfy the Like
comparison are returned.
来源:https://stackoverflow.com/questions/19147090/query-results-not-showing-records-with-null-values