萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

多條件動態資料庫查詢優化:字串組合法消除 IF 巢狀與分支爆炸

問題場景

使用者介面提供多個可選查詢條件 (如:姓名、性別、年齡),條件間為 **AND** 關係,使用者可任意組合 (0~N 個條件)。傳統寫法需列舉所有組合 (2^N 種),導致 SQL 分支爆炸、IF 巢狀地獄、維護困難。

傳統寫法痛點 (以 3 條件為例)

-- 8 個分支,3 層 IF 巢狀
IF A != '' AND B != '' AND C != '' THEN sql = "SELECT * FROM emp WHERE Name=A AND Sex=B AND Age=C"
ELSE IF A != '' AND B != '' THEN sql = "SELECT * FROM emp WHERE Name=A AND Sex=B"
ELSE IF A != '' AND C != '' THEN sql = "SELECT * FROM emp WHERE Name=A AND Age=C"
... (共 8 種組合) ...

條件增至 5 個 → 32 分支,10 個 → 1024 分支,**指數級爆炸**。

優化核心思想:動態構建 WHERE 子句字串

引入單一字串變數 whereClause,依序累加條件,最終拼接完整 SQL。

偽代碼邏輯

whereClause = ""                           -- 1. 初始化空字串

IF A != '' THEN                             -- 2. 處理條件 A
    whereClause = "WHERE Name = '" + A + "'"
END IF

IF B != '' THEN                             -- 3. 處理條件 B
    IF whereClause == "" THEN
        whereClause = "WHERE Sex = '" + B + "'"
    ELSE
        whereClause = whereClause + " AND Sex = '" + B + "'"
    END IF
END IF

IF C != '' THEN                             -- 4. 處理條件 C
    IF whereClause == "" THEN
        whereClause = "WHERE Age = " + C
    ELSE
        whereClause = whereClause + " AND Age = " + C
    END IF
END IF

finalSQL = "SELECT * FROM employee " + whereClause  -- 5. 最終拼接

Delphi/C++Builder 實作範例

function BuildQuerySQL(const AName, ASex, AAge: string): string;
var
  whereClause: string;
begin
  whereClause := '';
  
  if AName <> '' then
    whereClause := 'WHERE Name = ' + QuotedStr(AName); // QuotedStr 自動處理單引號轉義
  
  if ASex <> '' then begin
    if whereClause = '' then
      whereClause := 'WHERE Sex = ' + QuotedStr(ASex)
    else
      whereClause := whereClause + ' AND Sex = ' + QuotedStr(ASex);
  end;
  
  if AAge <> '' then begin
    if whereClause = '' then
      whereClause := 'WHERE Age = ' + AAge  -- 數值型無需引號
    else
      whereClause := whereClause + ' AND Age = ' + AAge;
  end;
  
  Result := 'SELECT * FROM employee ' + whereClause;
end;

// 使用
ADOQuery1.SQL.Text := BuildQuerySQL(EditName.Text, ComboSex.Text, EditAge.Text);
ADOQuery1.Open;

進階:參數化查詢版本 (防 SQL 注入、效能更優)

function BuildParamQuery(const AName, ASex, AAge: string; out SQL: string; out Params: array of Variant): Integer;
var
  whereClause: string;
  paramList: TList;
  i: Integer;
begin
  whereClause := '';
  paramList := TList.Create;
  try
    if AName <> '' then begin
      if whereClause = '' then whereClause := 'WHERE Name = ?' else whereClause := whereClause + ' AND Name = ?';
      paramList.Add(AName);
    end;
    
    if ASex <> '' then begin
      if whereClause = '' then whereClause := 'WHERE Sex = ?' else whereClause := whereClause + ' AND Sex = ?';
      paramList.Add(ASex);
    end;
    
    if AAge <> '' then begin
      if whereClause = '' then whereClause := 'WHERE Age = ?' else whereClause := whereClause + ' AND Age = ?';
      paramList.Add(AAge);
    end;
    
    SQL := 'SELECT * FROM employee ' + whereClause;
    SetLength(Params, paramList.Count);
    for i := 0 to paramList.Count - 1 do Params[i] := paramList[i];
    Result := paramList.Count;
  finally
    paramList.Free;
  end;
end;

// 使用 (FireDAC/ADO 參數綁定)
var
  sql: string;
  params: array of Variant;
  i: Integer;
begin
  BuildParamQuery(EditName.Text, ComboSex.Text, EditAge.Text, sql, params);
  FDQuery1.SQL.Text := sql;
  for i := 0 to High(params) do FDQuery1.Params[i].Value := params[i];
  FDQuery1.Open;
end;

擴展:支援 OR、IN、LIKE、範圍查詢等複雜條件

type
  TCondition = record
    FieldName: string;
    Operator: string; // =, !=, >, <, >=, <=, LIKE, IN, BETWEEN
    Value: Variant;
    Logic: string;    // AND, OR (首個條件忽略)
  end;

function BuildComplexQuery(const BaseSQL: string; const Conditions: array of TCondition): string;
var
  whereClause: string;
  c: TCondition;
begin
  whereClause := '';
  for c in Conditions do begin
    if VarIsNull(c.Value) or (c.Value = '') then Continue;
    
    var condSQL: string;
    case UpperCase(c.Operator) of
      'LIKE':  condSQL := c.FieldName + ' LIKE ' + QuotedStr('%' + c.Value + '%');
      'IN':    condSQL := c.FieldName + ' IN (' + c.Value + ')'; // Value 應為 'a','b','c' 格式
      'BETWEEN': condSQL := c.FieldName + ' BETWEEN ' + c.Value; // Value 應為 '10 AND 20'
      else     condSQL := c.FieldName + ' ' + c.Operator + ' ' + QuotedStr(VarToStr(c.Value));
    end;
    
    if whereClause = '' then
      whereClause := 'WHERE ' + condSQL
    else
      whereClause := whereClause + ' ' + c.Logic + ' ' + condSQL;
  end;
  Result := BaseSQL + whereClause;
end;

效能與安全性效益對比

指標傳統 IF 巢狀字串組合法參數化組合法
代碼分支數2^NN (線性)N (線性)
IF 巢狀層數N1 (平坦)1 (平坦)
SQL 注入風險高 (字串拼接)高 (字串拼接)無 (參數綁定)
執行計畫重用差 (每組合不同 SQL 文本)差優 (相同參數化 SQL)
維護性極差良好優秀

結語

**動態構建 WHERE 子句字串** 是解決多條件查詢組合爆炸的經典模式,將複雜度從 O(2^N) 降為 O(N)。進階採用 **參數化查詢 + 條件物件陣列**,同時解決 SQL 注入、執行計畫重用、擴展性三大問題,是企業級資料存取層 (DAL) 的標準實作模式。

copyright © 萬盛學電腦網 all rights reserved