I have used this technique in the past, is this the best method of doing this?
The Key to it is:
A. using the following "aa" procedure which make reading so much easier.
B. If you build the SQL string using a query builder (like in MS Access), it is good to configure a utility to take the built SQL and reformat it so that the resulting SQL looks pretty much exactly like that below. (I use www.sqlinform.com but there are others, or you can do it manually)
C. By adding vbCrLf beofre each line, when the SQL string is built in VBA the resulting string can be output to the immediate window an easily read as it will have line brakes and line up nicely. (It's not rocket science)
Public Sub aa(ByRef a As String, ByVal b As String)
' This is deliberately not a function, although it behaves a bit like one
a = a & vbCrLf & b
End Sub
' The function is called in code like this:
Dim a as string
a = ""
aa a, " SELECT CUR.txtLevel AS [Current] "
aa a, " , NLPMi.strFullName AS [Full Name] "
aa a, " , NLPMi.DOB AS [Birthday] "
aa a, " , NLPMi.Surname AS [Surname Name] "
aa a, " , TOOLS.txtWCMTool "
aa a, " FROM ( ( ( tblPeopleWCMSKILLSByYear AS SKILLS"
aa a, " LEFT JOIN tblSkillLevels AS CUR "
aa a, " ON SKILLS.bytCurrentID = CUR.atnSkillLevelID
aa a, " ) "
aa a, " INNER JOIN [qrylstNames-LPMi] AS NLPMi "
aa a, " ON SKILLS.intPeopleID = NLPMi.atnPeopleRecID
aa a, " )"
aa a, " INNER JOIN tblWCMTools AS TOOLS "
aa a, " ON SKILLS.intWCMSkillID = TOOLS.atnWCMToolID"
aa a, " ) "
aa a, " WHERE ( ( (SKILLS.bytYearID) = YEAR(DATE())-2012 ) "
aa a, " AND CUR.txtLevel >= " & MyVariable1 & " "
aa a, " AND TOOLS.txtWCMTool = '" & MyVariable2 & "'"
aa a, " ) "
aa a, " ORDER BY NLPMi.strFullName"
aa a, " ", " & MyVariable3 & ""
aa a, " ;"
Note that:
the brackets for the table joins line up
I use uppercase aliases to re-inforce they are aliases and so that they stand out
Sometimes I add spaces to separate the key areas (SELECT, WHERE, GROUP BY, FROM etc), usually when it is along bit of code and possible is very dynamic (ie when it has a lot of variables that change how it is built )
In the SELECT, ORDER BY and GROUP BY clauses, I favour putting the commas that are needed between columns in front of the column name on the same line.
I don't like database tables have the type in their name ie strFullName. However, this is not my schema!
Harvey