
96
Chapter 6 Making Variables Dynamic
Dynamic SQL
Embedding SQL queries that use dynamic parameters is a powerful mechanism for
linking variable inputs to database queries. However, in more sophisticated
applications, you often want user inputs to determine not only the content of queries
but also the structure of queries.
Dynamic SQL allows you to dynamically determine (based on runtime parameters)
which parts of a SQL statement are sent to the database. So if a user leaves a search
field empty, for example, you can simply omit the part of the WHERE clause that
refers to that field. Or, if a user does not specify a sort order, you can omit the entire
ORDER BY clause.
Implementing dynamic SQL
You implement dynamic SQL in ColdFusion by using
cfif, cfelse, cfelseif
tags
to control how the SQL statement is constructed, for example:
<cfquery name="
queryname
" datasource="
datasourcename
"
>
...
Base SQL statement(s)
<cfif value operator value >
...
additional SQL statement(s)
</cfif>
</cfquery>
The following code creates an application that lets a user search the CompanyInfo
database for employees by first name, last name, minimum salary, contract status, or
any combination of these criteria.
WHERE Course_ID=<cfqueryparam
value="#Course_ID#"
cfsqltype="CF_SQL_INTEGER">
</cfquery>
Only select rows where the Course_ID
column equals the value of Course_ID
CFML local variable. Validate that the
variable value is an integer and, if
appropriate for the database driver, use a
bind parameter to associate the value
with the SQL statement.
<cfoutput query="getFirst">
<p>
Department Number: #number#<br>
Description: #descript#
</p>
</cfoutput>
For each row that matches the query,
output the contents of the number and
descript columns.
Code
Description
Содержание COLDFUSION 5-DEVELOPING
Страница 1: ...Macromedia Incorporated Developing ColdFusion Applications MacroMedia ColdFusion 5 ...
Страница 58: ...38 Chapter 3 Querying a Database ...
Страница 134: ...114 Chapter 7 Updating Your Database ...
Страница 210: ...190 Chapter 10 Reusing Code ...
Страница 232: ...212 Chapter 11 Preventing and Handling Errors ...
Страница 238: ...218 Chapter 12 Using the Application Framework ...
Страница 262: ...242 Chapter 12 Using the Application Framework ...
Страница 278: ...258 Chapter 13 Extending ColdFusion Pages with CFML Scripting ...
Страница 320: ...300 Chapter 15 Indexing and Searching Data ...
Страница 336: ...316 Chapter 16 Sending and Receiving E mail ...
Страница 374: ...354 Chapter 18 Interacting with Remote Servers ...