在运行时构造的 SQL 语句

执行即席分析的应用程序通常会在运行时生成 SQL 语句。 例如,电子表格可能允许用户选择要从中检索数据的列:

// SQL_Statements_Constructed_at_Run_Time.cpp  
#include <windows.h>  
#include <stdio.h>  
#include <sqltypes.h>  
  
int main() {  
   SQLCHAR *Statement = 0, *TableName = 0;  
   SQLCHAR **TableNamesArray, **ColumnNamesArray = 0;  
   BOOL *ColumnSelectedArray = 0;  
   BOOL  CommaNeeded;  
   SQLSMALLINT i = 0, NumColumns = 0;  
  
   // 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;  
   Statement = (SQLCHAR*)malloc(8);  
   strcpy_s((char*)Statement, 8, "SELECT ");  
  
   for (i = 0 ; i = NumColumns ; i++) {  
      if (ColumnSelectedArray[i]) {  
         if (CommaNeeded)  
            strcat_s((char*)Statement, sizeof(Statement), ",");  
         else  
            CommaNeeded = TRUE;  
         strcat_s((char*)Statement, sizeof(Statement), (char*)ColumnNamesArray[i]);  
      }  
   }  
  
   strcat_s((char*)Statement, 15, " FROM ");  
   // strcat_s((char*)Statement, 100, (char*)TableName);  
  
   // Execute the statement . It will be executed once, do not prepare it.  
   // SQLExecDirect(hstmt, Statement, SQL_NTS);  
}  

在运行时通常构造 SQL 语句的另一类应用程序是应用程序开发环境。 但是,它们构造的语句在要生成的应用程序中进行硬编码,这些语句通常可以对其进行优化和测试。

在运行时构造 SQL 语句的应用程序可以为用户提供极大的灵活性。 如前面的示例所示,它甚至不支持 WHERE 子句、 ORDER BY 子句或联接等常见作,在运行时构造 SQL 语句比硬编码语句要复杂得多。 此外,测试此类应用程序是有问题的,因为它们可以构造任意数量的 SQL 语句。

在运行时构造 SQL 语句的潜在缺点是构造语句所需的时间要长得多,而不是使用硬编码语句。 幸运的是,这很少令人担心。 与用户输入条件相比,此类应用程序往往是用户界面密集型的,并且应用程序构造 SQL 语句的时间通常很小。