Share via


Parameter Queries

In some cases you want to create a query that you can use many times, but with a different value each time. For example, you might frequently query a titles table to find all the books written by one author. You could run the same query for each request, except that the author's ID or name would be different each time.

To create a query that can have different values at different times, you use parameters in the query. A parameter is a placeholder for a value that is supplied when the query runs. An SQL statement with a parameter might look like the following, where "?" represents the parameter for the author's state:

  SELECT au_lname, au_fname
FROM state
WHERE state = ?

Where You Can Use Parameters

You can use parameters as placeholders for literal values — for either text or numeric values. Most commonly, parameters are used as placeholders in search conditions for individual rows or for groups (that is, in the WHERE or HAVING clauses of an SQL statement).

Some databases allow you to use parameters as placeholders in expressions . For example, you might want to calculate discounted prices by supplying a different discount value each time you run a query. To do so, you could specify the following expression:

  (price * ?)

For details about where you can use parameters, see Parameters.

Specifying Unnamed and Named Parameters

You can specify two types of parameters: unnamed and named. An unnamed parameter is a question mark (?) that you put anywhere in the query that you want to prompt for or substitute a literal value. For example, if you use an unnamed parameter to search for an author's id in a titles table, the resulting statement in the SQL pane might look like this:

  SELECT au_lname, au_fname
FROM state
WHERE state = ?

When you run the query in the Query Designer, the Define Query Parameters dialog box appears with "?" as the name of the parameter, as in the following illustration.

Alternatively, you can assign a name to a parameter. Named parameters are particularly useful if you have multiple parameters in a query. For example, if you use named parameters to search for an author's first and last names in an authors table, the resulting statement in the SQL pane might look like this:

  SELECT au_id
FROM authors
WHERE au_fname = %first name% AND
  au_lname = %last name%

When you run the query in the Query Designer, the Define Query Parameters dialog box appears with a list of named parameters, as in the following illustration.

See Also

Creating a Query with Named Parameters | Creating a Query with Unnamed Parameters | Creating General Purpose Queries | Specifying Parameter Marker Characters | Supported Query Types