You are on page 1of 3

Tutor.MAY...

NEW@ 14/05/01 8:15 PM Page 2

MAY TUTOR ■
ACCESS SQL

easing
into sql
T h e re’s good reason for Access pro g ra m m e rs to learn SQL. The Access query design
grid lets you construct complicated SQL st at e m e n ts with minimal diffi c u l t y. Here’ s
h ow to keep your queries error and bug fre e .

astering Access SQL (Structured such, prone to logic errors and typos, so let In many cases, the resulting statement will

M Query Language) can be a daunt-


ing task even if you consider your-
self an Access expert. Part of the
Access do as much of the work for you as pos-
sible. Fortunately, you can create most basic
statements in the query design grid. Access
need some fine tuning. Unless you’re very adept
at writing SQL statements, though, you’ll prob-
ably find this quick-start method preferable to
problem is the absence of an Access-to-SQL produces an equivalent SQL statement for every writing the entire statement from scratch.
interface. This limitation doesn’t have to slow query, and you can use this behaviour to your
you down, however, if you know how to avoid advantage. To build a SQL statement in the DEBUG A SQL STATEMENT IN THE QUERY
some of the more common coding mistakes. In query design grid, begin as you would with DESIGN GRID
this article, we’ll show you how to use the query any normal query by choosing a data source If you make any changes to a SQL statement
design grid to create SQL statements and then (table or query), clicking on the New Object after copying it from the design grid to a mod-
how to run the statements in the Immediate button in the Database toolbar and selecting ule, chances are the statement won’t run cor-
window to debug them. Query. (In Access 97, you would select the rectly the first time. Unfortunately, VBA error
You might be wondering why you should Queries tab and click the New button.) messages aren’t very helpful in this context.
bother to learn SQL at all. One reason is that Once you have a data source and have On the other hand, the query design grid is
almost any bound object will accept a SQL opened the query design grid, drag fields from almost always helpful and informative. If you
statement as its data source. Consequently, you the field list to the grid, build relationships, add can’t quickly figure out the problem, copy the
can often replace a fixed query with a simple criteria and specify sort orders. Along the way, SQL statement from the module to the query
SQL statement. In addition, some queries sim- feel free to view the results of the query by design grid and run the statement there. The
ply can’t be replicated in the query design grid. clicking the View button and choosing same error will occur, but the query design
Only a SQL statement can implement a Union Datasheet View. grid’s error message will be more specific and
query, for instance. Once you’re familiar with When you’ve gone as far as you can using the will usually help you pinpoint the mistake.
SQL, you’ll find many convenient uses for it. grid – you may not be able to create the com- If you’d like to try this yourself, here’s a short
plete statement – click the View button and list of instructions that will help you through the
BUILD A SQL STATEMENT IN THE QUERY choose SQL View and Access will display the process:
DESIGN GRID query’s equivalent sql statement. Finally, high- 1. Highlight the SQL statement in the module.
SQL statements can be extremely long and, as light the statement and copy it to a module. Don’t include the quotation marks at the begin-

106 May 2001 www.DITnet.co.ae ■ www.pcmag-mideast.com


Tutor.MAY...NEW@ 14/05/01 8:15 PM Page 3

■ MAY TUTOR
ACCESS SQL

ning or the end of the statement or the VBA


method (Run SQL or Execute) you’re using to
run the SQL statement.
2. Press Ctrl-C or, alternatively, choose Copy
from the Edit menu.
CAREFUL CONCATENATION
3. Access the Database window (press F11 to
restore the window if it’s minimised). One of the most typical SQL mis- this error in the basic statement,
4. Choose Query from the Object bar and then takes isn’t even a SQL error; it’s a though, so you can spend a lot of
click New in the Database window toolbar. concatenation error. Omitting the time rewriting the statement with-
(Access 97 users should click the Queries tab necessary spaces between the SQL out ever correcting the actual error.
and then click the New button in the Database statement and the variables you’re The correct statement
window.) concatenating, for example, is com- db.Execute "SELECT * INTO " &
5. In the resulting new query dialog, double mon. The seemingly correct state- tblNewTable & " FROM tblOld-
click Design View. ment Table WHERE tblOldTable.Last-
6. When Access opens the query design grid, d b . E x e c u t e " S E L E C T * I N T OName”
" & & strCriteria & ";" should
close the Show Table dialog without selecting tblNewTable & "FROM tblOldTable run, provided strCriteria is valid.
a data source. WHERE tblOldTable.LastName" & If you have too much trouble with
7. Click the View button in order to open the strCriteria & won’t" ; "work concatenation, consider defining a
SQL window. because there’s no space between constant that consists of a space
8. Press Ctrl-V or choose Paste from the Edit the INTO keyword and the table ch a ra c t e r, and use the const a n t
menu in order to copy the SQL statement to name. There’s also space missing instead of a space. This can make
the SQL window. between the table name and the your statement more readable and
9. Replace any variables with the appropriate FROM clause. Let’s take a look at therefore a bit easier to debug. For
object names. how this statement evaluates, so instance, after defining the space
10. Select Query | Run from the Access menu you can see the actual error. character as a constant using the
bar (or click Run on the Query Design tool- Let’s suppose you’re creating a statement Const conSpace = " "
bar.) new table named tblNewTable with you can include the constant in the
records from tblOldTable that con- statement
In step 9, we note that you must replace vari- tain “Smith” in the LastName field. db.Execute "SELECT * INTO" &
ables with the actual object names they repre- In this case, the SQL st at e m e n t conSpace & tblNewTable& con-
sent. For example, the statement: above would evaluate to SELECT * S p a c e & “ F R O M t b l O l d T a b l e
SELECT * FROM " & strTable & " I N T O t b l N e w T a b l e F R O M t b l O lWHERE
d- tblOldTable.LastName" &
would return an error if you tried to run it as is Table WHERE tblOldTable. Last-strCriteria & ";"
in the query design grid. You must replace the Name = 'Smith'; Some might consider this approach
variable strTable with an actual table or query Evaluated, the missing spaces are overkill, but the solution that works
name. Let’s suppose you’re working with a easy to spot. You can’t readily see for you is what you should use.
table named tblMyTable. You’d replace the “ &
strTable & “ section of your statement with the
table’s name as follows:
SELECT * FROM tblMyTable essary corrections to the statement in the mod- hence additional errors) into your statement.
After replacing all the variables with actual ule (as long as the concatenated variables The code that follows shows an example of
object names, run the statement by clicking the weren’t part of the original problem). this easy trick:
Run button on the Query Design toolbar. If the strCriteria = " = 'Smith'"
grid evaluates the statement without returning AVOID CONCATENATION ERRORS strSQL = "SELECT * INTO tblNewTable FROM
an error, you can assume your problem was Using the query design grid to track down prob- tblOldTable WHERE " & "tblOldTable
with the variables. If not, most likely there’s a lems in SQL statements is a great trick, but .LastName" & strCriteria & ";"
simple problem with the delimiting characters replacing the variables first can be a pain. You Debug.Print strSQL
(which we’ll discuss in the next section). can easily make a mistake in the process and The first two lines assign the search criteria
When variables aren’t the problem, Access not know it, further complicating your debug- and the basic SQL statement to the string vari-
will almost always display a more compre- ging task. ables strCriteria and strSQL. The Debug.Print
hensive error message than you received from You can avoid the variable problem by statement then prints the evaluated statement
vba. For instance, if your statement contains a adding a few extra lines of code to your VBA to the Immediate window. If the statement
syntax error, Access usually indicates the procedure. The additional code will print an returns an error, open the Immediate window
offending section – significantly narrowing evaluated SQL statement in the Immediate win- (by pressing Ctrl-G or clicking the Code button,
your search. At this point, you should be able dow. By evaluated, we mean that VBA will depending on what window is active). Now
to spot your mistake and make the necessary replace all of the variables with the appropri- copy the evaluated version
changes. ate object names. Copying the evaluated ver- SELECT*INTOtblNewTableFROMtblOldTable
Keep working with the statement until you sion from the Immediate window to the query WHERE tblOldTable.LastName = 'Smith';
receive no errors, then copy the corrected state- design grid relieves you of the aggravating task to the query design grid (instead of copying
ment back to the module and restore any vari- of replacing the variables and completely elim- the original statement from the VBA module)
ables you replaced in step 9. Or make the nec- inates the possibility of introducing typos (and and run it there. Notice that the evaluated ver-

www.DITnet.co.ae ■ www.pcmag-mideast.com May 2001 107


Tutor.MAY...NEW@ 14/05/01 8:15 PM Page 4

MAY TUTOR ■
ACCESS SQL

sion includes the actual name of the data source view this query’s SQL statement, shown in Fig- your changes when prompted. The control will
and the criteria string, not the variables shown ure 2, by choosing SQL View from the View update accordingly.
in the code listing above. button at the far left of the toolbar. You can SQL can be difficult to work with; even the
Not only is this solution easier, but you avoid also see the results of the query by choosing experts occasionally fret over a statement. For-
introducing typos. Don’t wait until you have a Datasheet View. tunately, Access offers a number of tools to
problem with a SQL statement, though; get in As you can see, this builder is flexible – you make the task easier. The query design grid
the habit of adding this functionality to your can view three different forms of the same gives you an easier way to create SQL state-
code so it’s available when you need it. query. You can bounce back and forth between ments than trying to create them from scratch.
the builder, the SQL statement, and the results In addition, you can debug statements by copy-
QUICK RESULTS WITH THE QUERY BUILDER until you get the statement just right, at which ing evaluated statements from the Immediate
Access SQL isn’t limited to queries and VBA time you simply close the builder and save window to the query design grid.
modules; controls often use a SQL statement
instead of a saved query as the Row Source
property. Fortunately, you don’t have to create
the appropriate statement from scratch; you
can use the SQL statement query builder. (We’ll
show you how to access this builder in just a
minute.) In the open builder, you’ll choose
fields and express criteria in the query design
grid, just as you would in a normal query. The
builder then converts your work into a SQL
statement. You don’t actually have to know Figure 1: The SQL Statement Query Builder launches a query design grid.
SQL at all.
Let’s take a look at an example. Open in
Design View any form that contains a combo
or list box, or open a blank form and add a
combo or list box. Double click the combo or
list box to open its property sheet, and click the
Build button that appears when you select the
Row Source property field. This launches the
SQL statement query builder, which is a sim-
ple query design grid. Modify the grid as you
would a query. (If you’re working with an
existing control, the grid will display an equiv-
alent sql statement in the query design grid.)
Figure 1 shows a simple expression that will
display a list of concatenated fields – FirstName
and LastName. In other words, the combo or
Figure 2: The query in Figure 1 and the SQL statement here represent the same question.
list control will display a list of names. You can

See this month’s reader response card and you could win one of these fantastic prizes.

WIN!

You might also like