Building Dynamic SQL Statements

You can reference ColdFusion variables in SQL statements to dynamically filter the query result set at run-time. This is referred to as dynamic SQL statements.

For example, you may want to reference Form and URL variables in a SELECT statement to return a result set that is associated with a value that a user entered on an associated form page.

When writing dynamic SQL statements:

Dynamic SQL usage example

The action page code below retrieves database records whose LastName field match the value that users entered in the LastName form field - a form variable that passed to this action page when the user submitted a form:

SELECT FirstName, LastName, StartDate, Salary, Contract
FROM Employees
WHERE LastName= '#Form.LastName#'

If the user entered Allaire in the LastName form field, the SQL statement sent to the database at run-time would be:

SELECT FirstName, LastName, StartDate, Salary, Contract
FROM Employees
WHERE LastName= 'Allaire'
Note Note:You will learn more about HTML forms and ColdFusion action pages in Chapter 7, Using Forms and Action Pages and more about generating dynamic SQL statements in Chapter 9, Building Search Interfaces.