Managing and debugging SQL queries in MS Access

后端 未结 9 2076
既然无缘
既然无缘 2020-11-21 22:08

MS Access has limited capabilities to manage raw SQL queries: the editor is quite bad, no syntax highlighting, it reformats your raw SQL into a long string and you can\'t in

9条回答
  •  臣服心动
    2020-11-21 22:39

    I have a few tips that are specific to SQL in VBA.

    Put your SQL code with a string variable. I used to do this:

    DoCmd.RunSQL "SELECT ..."
    

    That is hard to manage. Do this instead:

    strSQL = "SELECT ..."
    DoCmd.RunSQL strSQL
    

    Often you can't fix a query unless you see just what's being run. To do that, dump your SQL to the Immediate Window just before execution:

    strSQL = "SELECT ..."
    Debug.Print strSQL
    Stop
    DoCmd.RunSQL strSQL
    

    Paste the result into Access' standard query builder (you must use SQL view). Now you can test the final version, including code-handled variables.

    When you are preparing a long query as a string, break up your code:

    strSQL = "SELECT wazzle FROM bamsploot" _
          & vbCrLf & "WHERE plumsnooker = 0"
    

    I first learned to use vbCrLf when I wanted to prettify long messages to the user. Later I found it makes SQL more readable while coding, and it improves the output from Debug.Print. (Tiny other benefit: no space needed at end of each line. The new line syntax builds that in.)

    (NOTE: You might think this will let you add add comments to the right of the SQL lines. Prepare for disappointment.)

    As said elsewhere here, trips to a text editor are a time-saver. Some text editors provide better syntax highlighting than the official VBA editor. (Heck, StackOverflow does better.) It's also efficient for deleting Access cruft like superfluous table references and piles of parentheses in the WHERE clause.

    Work flow for serious trouble shooting:

    VBA Debug.Print >       (capture query during code operation)
      query builder   >     (testing lab to find issues)
         Notepad++      >   (text editor for clean-up and review)
      query builder   >     (checking, troubleshooting) 
    VBA
    

    Of course, trouble shooting is usually a matter of reducing the complexity of a query until you're able to isolate the problem (or at least make it disappear!). Then you can build it back up to the masterpiece you wanted. Because it can take several cycles to solve a sticky problem, you are likely to use this work flow repeatedly.

提交回复
热议问题