Multiple parameter query; ignore blanks & have results match all parameters entered

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • katlee
    New Member
    • Jul 2010
    • 10

    Multiple parameter query; ignore blanks & have results match all parameters entered

    I am using Access 2007 to design a database that will allow users to search an inventory of historical photographs. Currently I have a table with fields such as Date, ID, Description, Project, Division, Unit, Facility, Feature, Subfeature, Region, Area Office, and State. I am using a query by form method that have either text boxes or combo boxes for each of the fields. I want users to be able to enter in the fields that they want to search by and leave others blank. I want the query to disregard the parameters left blank and then display the results that match ALL the parameters entered. For example I want to be able to enter a date range, Project Name, and Region and want the results to match all three criteria not all the records within the date range plus all records associated with the project plus all records from the specified region. I think it may have something to do with the use of AND and OR. If anyone has any words of wisdom it would be greatly appreciated. This is what I have come up with so far:

    Code:
    SELECT [ID]
          ,[Project]
          ,[Division]
          ,[Unit]
          ,[Feature]
          ,[Subfeature]
          ,[Region]
          ,[Spec No]
          ,[State]
          ,[Date]
          ,[Description]
          ,[Photographer]
          ,[Field1]
          ,[Latitude]
          ,[Longitude]
          ,[Facility]
          ,[AreaOffice]
    
    FROM   [Historical Photos]
    
    WHERE  (([Project]=[Forms]![Search]![txtProject]) OR ([Forms]![Search]![txtProject] Is Null)
      AND  ([Division]=[Forms]![Search]![txtDivision]) OR ([Forms]![Search]![txtDivision] Is Null)
      AND  ([Unit]=[Forms]![Search]![txtUnit]) OR ([Forms]![Search]![txtUnit] Is Null)
      AND  ([ID]=[Forms]![Search]![txtPhotoID]) OR ([Forms]![Search]![txtPhotoID] Is Null)
      AND  ([Feature]=[Forms]![Search]![txtFeature]) OR ([Forms]![Search]![txtFeature] Is Null)
      AND  ([Subfeature]=[Forms]![Search]![txtSubfeature]) OR ([Forms]![Search]![txtSubfeature] Is Null)
      AND  ([Facility]=[Forms]![Search]![txtFacility]) OR ([Forms]![Search]![txtFacility] Is Null)
      AND  ([State]=[Forms]![Search]![cboState]) OR ([Forms]![Search]![cboState] Is Null)
      AND  ([Region]=[Forms]![Search]![cboRegion]) OR ([Forms]![Search]![cboRegion] Is Null)
      AND  ([AreaOffice]=[Forms]![Search]![cboAreaOffice]) OR ([Forms]![Search]![cboAreaOffice] Is Null)
      AND  ([Description] Like "*" & [Forms]![Search]![txtDescription] & "*") OR ([Forms]![Search]![txtDescription] Is Null)
      AND  ([Date] Between [Forms]![Search]![txtStart] AND [Forms]![Search]![txtEnd]) OR ([Forms]![Search]![txtStart] Is Null OR [Forms]![Search]![txtEnd] Is Null));
    Last edited by NeoPa; Jul 15 '10, 04:26 PM. Reason: I tidied up your SQL so it could be read. Please use the [CODE] tags provided.
  • colintis
    Contributor
    • Mar 2010
    • 255

    #2
    Try using LIKE and Nz function in your query like this, I'll only take your first parameter and the date parameter for the example:
    Code:
    WHERE (([Historical Photos].Project) LIKE '" & Nz([Forms]![Search]![txtProject],"*") & "')
    AND (([Historical Photos].Date) >= LIKE '# & Nz([Forms]![Search]![txtStart],"*") & #')
    AND (([Historical Photos].Date) <= LIKE '# & Nz([Forms]![Search]![txtEnd],"*" & #')
    Take notice on the quotes, the [" &] and [& "] is used for strings. The date I would try with this method as I haven't tried using the BETWEEN function with LIKE. And also the brackets, make sure they are closed to the correct ones.

    Reference for Nz function:
    This MSAccess tutorial explains how to use the Access Nz function with syntax and examples. The Microsoft Access Nz function lets you return a value when a variant is null.

    Finally, quote the codes to the CODE TAG.

    Comment

    • katlee
      New Member
      • Jul 2010
      • 10

      #3
      I used what you gave me and this error message "Syntax error (missing operator) in query expression" came up and it highlighted LIKE.

      Comment

      • katlee
        New Member
        • Jul 2010
        • 10

        #4
        Also I tried
        Code:
        WHERE ((([Historical Photos].Project) Like '" & Nz([Forms]![Search]![txtProject],"*") & "') AND (([Historical Photos].Division) Like '" & Nz([Forms]![Search]![txtDivision],"*") & "'));
        as a test because there was no syntax error and the query returned zero results when entering just one parameter and zero results when entering both parameters.
        Last edited by NeoPa; Jul 15 '10, 04:16 PM. Reason: Please use the [CODE] tags provided.

        Comment

        • colintis
          Contributor
          • Mar 2010
          • 255

          #5
          Originally posted by katlee
          Also I tried

          WHERE ((([Historical Photos].Project) Like '" & Nz([Forms]![Search]![txtProject],"*") & "') AND (([Historical Photos].Division) Like '" & Nz([Forms]![Search]![txtDivision],"*") & "'));

          as a test because there was no syntax error and the query returned zero results when entering just one parameter and zero results when entering both parameters.
          Can you try removing the --> ,"*" <-- in the Nz function? the "*" may be identified as a value instead of a null.

          Or in a more complicate method is to create a filter condition statement in VBA. using something like this with DAO:
          Code:
          Dim firstCond As Boolean = False
          Dim strSQL As String
          strSQL = "SELECT [blah blah blah] " & _
                   "FROM [Historical Photos] " & _
                   "WHERE "
          If Not IsNull([Forms]![Search]![txtProject]) Then
              strSQL = strSQL & "[Historical Photos].Project = [Forms]![Search]![txtProject"
          End If

          Comment

          • katlee
            New Member
            • Jul 2010
            • 10

            #6
            I tried removing "*" and the query still didn't return any results.

            I thought there may be a way to do it using VBA but I have never done anything with VBA and am a little intimidated. Would I write this code in the "On Click" event of a button on the form where the users enter the parameters?

            Right now I have a form thats record source is the query and am using a macro to get it to pop up and display the results. Is there a way to get this same effect using VBA?

            Also, would I use what I had originally in the WHERE or use your suggestion (Like Nz)...
            Code:
            strSQL = "SELECT [blah blah blah] " & _ 
                     "FROM [Historical Photos] " & _ 
                     "WHERE " (what goes here?)
            Thank you so much for your time!!!!
            Last edited by NeoPa; Jul 15 '10, 04:17 PM. Reason: Please use the [CODE] tags provided.

            Comment

            • colintis
              Contributor
              • Mar 2010
              • 255

              #7
              Originally posted by katlee
              I tried removing "*" and the query still didn't return any results.

              I thought there may be a way to do it using VBA but I have never done anything with VBA and am a little intimidated. Would I write this code in the "On Click" event of a button on the form where the users enter the parameters?

              Right now I have a form thats record source is the query and am using a macro to get it to pop up and display the results. Is there a way to get this same effect using VBA?

              Also, would I use what I had originally in the WHERE or use your suggestion (Like Nz)...

              strSQL = "SELECT [blah blah blah] " & _
              "FROM [Historical Photos] " & _
              "WHERE " (what goes here?)

              Thank you so much for your time!!!!
              Yes you can do that on_click event in VBA, if you want more basic reference on how to program VBA, you can click THIS LINK.

              The method of working out your filter criterias have 2 methods, one is by ADO, and one is by DAO. Both works the same to connect a table, what different is the way to store the data into the table. The one I wrote above was using a DAO method, when there's a true to one of the IF criteria, it will append the filter into the SQL WHERE clause.

              For the click event in VBA code with your requirements, it would be roughly in these steps to proceed.
              =============== =============== =========
              1. Declare the variable to store strings, connections, etc
              2. Connect to the database table
              3. run through the if-else statements to append addition criterias into the SQL string
              4. Start executing the SQL
              5. when the things are complete, use MsgBox to create pop-up message.

              Comment

              • NeoPa
                Recognized Expert Moderator MVP
                • Oct 2006
                • 32633

                #8
                Colintis is broadly leading you along the right lines here, but it will always be complicated working with such a full set of SQL. I would suggest simplifying the problem, until the fundamental points are understood, then maybe expanding that new understanding to rebuild the full query. Let's start then with :
                Code:
                SELECT [ID]
                      ,[Project]
                      ,[Date]
                      ,[Description]
                
                FROM   [Historical Photos]
                
                WHERE  (([ID]=[Forms]![Search]![txtPhotoID]) OR ([Forms]![Search]![txtPhotoID] Is Null)
                  AND  ([Project]=[Forms]![Search]![txtProject]) OR ([Forms]![Search]![txtProject] Is Null)
                  AND  ([Date] Between [Forms]![Search]![txtStart] And [Forms]![Search]![txtEnd]) OR ([Forms]![Search]![txtStart] Is Null OR [Forms]![Search]![txtEnd] Is Null))
                  AND  ([Description] Like '*' & [Forms]![Search]![txtDescription] & '*') OR ([Forms]![Search]![txtDescription] Is Null);
                The first point to note is that the following two are not equivalent (with reference to your WHERE clause) :
                Code:
                    ((A=1) OR (A Is Null)
                AND (B=1) OR (B Is Null)
                AND (C=1) OR (C Is Null))
                Code:
                    (((A=1) OR (A Is Null))
                AND ((B=1) OR (B Is Null))
                AND ((C=1) OR (C Is Null)))
                In the latter the matching sets of comparisons are linked together by parentheses. This would be important if we wanted to proceed in this way, and would certainly explain why your SQL was giving unexpected results (With reference to your question about ANDs and ORs).

                Borrowing from Colintis, we can actually be a little more clever than that, and do a single comparison that handles the situation where the form's control is unset :
                Code:
                SELECT [ID]
                      ,[Project]
                      ,[Date]
                      ,[Description]
                
                FROM   [Historical Photos]
                
                WHERE  (([ID] Like Nz([Forms]![Search]![txtPhotoID],'*'))
                  AND  ([Project] Like Nz([Forms]![Search]![txtProject],'*'))
                  AND  ([Date] Between Nz([Forms]![Search]![txtStart],#1/1/1900#)
                                   And Nz([Forms]![Search]![txtEnd],#31/12/9999#))
                  AND  ([Description] Like '*' & Nz([Forms]![Search]![txtDescription],'*') & '*'))
                Does this make things a little clearer?
                Last edited by NeoPa; Jul 16 '10, 08:55 PM. Reason: Added missing closing parentheses in last WHERE clause

                Comment

                • katlee
                  New Member
                  • Jul 2010
                  • 10

                  #9
                  The query seems to be working how it is supposed to! Hopefully I can apply this method to include all the fields.. Thanks to colintis for your patience and Neopa for breaking it down into simpler terms for such a beginner! What a valuable resource this forum is :)

                  Comment

                  • NeoPa
                    Recognized Expert Moderator MVP
                    • Oct 2006
                    • 32633

                    #10
                    You're very welcome Katlee :)

                    Comment

                    • katlee
                      New Member
                      • Jul 2010
                      • 10

                      #11
                      Spoke a little too soon.. I have three combo boxes (cboState, cboAreaOffice, cboRegion) that have queries of my master table as their source..
                      Code:
                      AND ([Region] Like Nz ([Forms]![Search]![cboRegion],"*") AND ([AreaOffice] Like Nz ([Forms]![Search]![cboAreaOffice],"*")
                      ... is what I am using now and I get the expected results when selected one state but not the other. Do I need to do something different?

                      Comment

                      • NeoPa
                        Recognized Expert Moderator MVP
                        • Oct 2006
                        • 32633

                        #12
                        Katlee, Your SQL doesn't include anything for State, and I have no information as to what States are one or the other.

                        This leaves me somewhat short of information :D

                        Comment

                        • katlee
                          New Member
                          • Jul 2010
                          • 10

                          #13
                          Sorry
                          Code:
                          AND ([Region] Like Nz ([Forms]![Search]![cboRegion],"*") 
                          AND ([AreaOffice] Like Nz ([Forms]![Search]![cboAreaOffice],"*") 
                          AND ([State] Like Nz ([Forms]![Search]![cboState],"*")
                          To be more specific, I have a dummy set of records right now that I am using to see if the query will work. Currently, records have either "CA" or "AZ" for the state (when the database is in use records will be from all over the US). Using this SQL when choosing "AZ" the query worked fine, but "CA" did not return any records...

                          Comment

                          • NeoPa
                            Recognized Expert Moderator MVP
                            • Oct 2006
                            • 32633

                            #14
                            No worries Katlee.

                            Now you've formulated the SQL readably though, the answer (problem) jumps out.

                            The closing parenthesis on each line deals only with the Nz() function call. A further closing parenthesis is required to close each sub-statement.

                            BTW It's not wrong, but possibly unusual, to leave a space after Nz and before the open parenthesis. That's just display though. SQL will handle it either way.

                            PS. I just checked too, and my suggestion was what led you astray. I didn't include the second closing parenthesis on any of the lines so I will fix that now. It may be fixed by the time you read this, but it certainly was there when you read it. Just so you know (but I don't want to leave misinformation in my post).
                            Last edited by NeoPa; Jul 16 '10, 04:24 PM.

                            Comment

                            • katlee
                              New Member
                              • Jul 2010
                              • 10

                              #15
                              Ok, makes sense!! My SQL is currently
                              Code:
                              WHERE (([ID] Like Nz([Forms]![Search]![txtPhotoID],"*")) 
                              AND ([Project] Like Nz([Forms]![Search]![txtProject],"*")) 
                              AND ([Date] Between Nz([Forms]![Search]![txtStart],#1/1/1900#) 
                              And Nz([Forms]![Search]![txtEnd],#31/12/9999#)) 
                              AND ([Description] Like "*" & Nz([Forms]![Search]![txtDescription],"*") & "*")) 
                              AND ([Division] Like Nz([Forms]![Search]![txtDivision], "*")) 
                              AND ([AreaOffice] Like Nz([Forms]![Search]![cboAreaOffice], "*")) 
                              AND ([Region] Like Nz([Forms]![Search]![cboRegion], "*")) 
                              AND ([State] Like Nz([Forms]![Search]![cboState], "*"));
                              ... but something strange and perhaps unrelated to the SQL is happening. I have a 8 records with the "CA" in the State field, "Mid-Pacific" in the Region field, and "South-Central California" for the AreaOffice field, but when I select these choices from the combo boxes the query only returns 3 records... any suggestions?

                              Edit:
                              I realized that what the three records have in common is they have values in all the other fields being queried (none of the fields were left blank in the table)... the problem is that some records will not have values in a certain field because the information is unknown. For example, very old photographs were assigned Photo IDs and in a certain year this stopped being done. I want users to be able to search by the ID if they know it, but if they want all the records from a certain time period (without knowing and ID) they could enter that and records with or without a Photo ID would be returned (currently only the ones with an ID within that time period are being returned. I hope this makes sense :/

                              Comment

                              Working...