使用者介面提供多個可選查詢條件 (如:姓名、性別、年齡),條件間為 **AND** 關係,使用者可任意組合 (0~N 個條件)。傳統寫法需列舉所有組合 (2^N 種),導致 SQL 分支爆炸、IF 巢狀地獄、維護困難。
-- 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 分支,**指數級爆炸**。
引入單一字串變數 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. 最終拼接
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;
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;
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^N | N (線性) | N (線性) |
| IF 巢狀層數 | N | 1 (平坦) | 1 (平坦) |
| SQL 注入風險 | 高 (字串拼接) | 高 (字串拼接) | 無 (參數綁定) |
| 執行計畫重用 | 差 (每組合不同 SQL 文本) | 差 | 優 (相同參數化 SQL) |
| 維護性 | 極差 | 良好 | 優秀 |
**動態構建 WHERE 子句字串** 是解決多條件查詢組合爆炸的經典模式,將複雜度從 O(2^N) 降為 O(N)。進階採用 **參數化查詢 + 條件物件陣列**,同時解決 SQL 注入、執行計畫重用、擴展性三大問題,是企業級資料存取層 (DAL) 的標準實作模式。