SQL Statements Constructed at Run Time
SQLCHAR **TableNamesArray, **ColumnNamesArray;
BOOL *ColumnSelectedArray;
BOOL CommaNeeded;
SQLSMALLINT i, NumColumns;
// Use SQLTables to build a list of tables (TableNamesArray[]). Let the user
select a
// table and store the selected table in TableName.
// Use SQLColumns to build a list of the columns in the selected table
// (ColumnNamesArray). Set NumColumns to the number of columns in the table.
Let the
// user select one or more columns and flag these columns in
ColumnSelectedArray[].
// Build a SELECT statement from the selected columns.
CommaNeeded = FALSE;
strcpy(Statement, "SELECT ");
for (i = 0; i = NumColumns; i++) {
if (ColumnSelectedArray[i]) {
if (CommaNeeded)
strcat(Statement, ",");
else
CommaNeeded = TRUE;
strcat(Statement, ColumnNamesArray[i]);
}
}
strcat(Statement, " FROM ");
strcat(Statement, TableName);
// Execute the statement directly. Because it will only be executed once, do
not
// prepare it.
SQLExecDirect(hstmt, Statement, SQL_NTS);
Applications that construct SQL statements at run time can provide tremendous
flexibility to the user. As can be seen from the preceding example, which did
not even support such common operations as WHERE clauses, ORDER BY clauses, or joins, constructing SQL statements at run time is vastly more
complex than hard-coding statements. Furthermore, testing such applications is
problematic, as they can construct an arbitrary number of SQL statements.
A potential disadvantage of constructing SQL statements at run time is that it
takes far more time to construct a statement than use a hard-coded statement.
Fortunately, this is rarely a concern. Such applications tend to be very user
interface intensive and the time the application spends constructing SQL
statements is generally small compared to the time the user spends entering criteria.