Build SQL Statements That Include Variables and Controls

Build SQL Statements That Include Variables and Controls

See Also

When working with Data Access Objects (DAO), you may need to construct an SQL statement in code. For example, if you're creating a new QueryDef object, you must set its SQL property to a valid SQL string. You're also likely to need an SQL statement when creating a Recordset object.

The easiest way to construct an SQL statement is to create a query in the query design grid, switch to SQL view, and copy and paste the corresponding SQL statement into your code.

Often a query must be based on values that the user supplies, or that change in different situations. If this is the case, you'll need to include variables or control values in your query. The Microsoft Jet database engine processes all SQL statements, but not variables or controls. Therefore, you must construct your SQL statement so that Microsoft Access first determines these values and then concatenates them into the SQL statement that's passed to the Jet database engine.

The following example shows how to create a QueryDef object with a simple SQL statement. This query returns all orders from an Orders table that were placed after 3-31-96:

Dim dbs As Database, qdf As QueryDef, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT * FROM Orders WHERE OrderDate >#3-31-96#;"
Set qdf = dbs.CreateQueryDef("SecondQuarter", strSQL)

The next example creates the same QueryDef object by using a value stored in a variable. Note that the number signs (#) that denote the date values must be included in the string so that they are concatenated with the date value.

Dim dbs As Database, qdf As QueryDef, strSQL As String
Dim dteStart As Date
dteStart = #3-31-96#
Set dbs = CurrentDb
strSQL = "SELECT * FROM Orders WHERE OrderDate" _
    & "> #" & dteStart & "#;"
Set qdf = dbs.CreateQueryDef("SecondQuarter", strSQL)

The following example creates a QueryDef object by using a value in a control called OrderDate on an Orders form. Note that you provide the full reference to the control, and that you include the number signs that denote the date within the string.

Dim dbs As Database, qdf As QueryDef, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT * FROM Orders WHERE OrderDate" _
    & "> #" & Forms!Orders!OrderDate & "#;"
Set qdf = dbs.CreateQueryDef("SecondQuarter", strSQL)