为 Access 重构 T-SQL 中的 WHERE 子句
Refactoring WHERE clause in T-SQL for Access
我目前正在实施一个涉及 table 中 30 个字段的重型 WHERE
子句,有没有办法重构:
WHERE (
(table.field1 LIKE "*" & Forms!SearchForm!txt_box1 & "*"
Or Forms!SearchForm!txt_box1 Is Null)
AND (table.field2 LIKE "*" & Forms!SearchForm!txt_box2 & "*"
Or Forms!SearchForm!txt_box2 Is Null)
AND ...
依此类推,直到我到达最后一个字段 (31)。关于如何在这里实现 DRY 方法的任何想法?
我通常做的是将每个控件命名为与要包含在过滤器中的字段相同的名称,并将标记 属性 设置为数据类型。然后遍历控件。
Dim ctL As Access.Control
Dim strWhere As String
For Each ctL In Me.Controls
If ctL.ControlType = acTextBox Or ctL.ControlType = acComboBox Then
If Nz(ctL,"") <> "" Then
strWhere = strWhere & " AND " & ctL.Name & "="
If ctL.Tag = "Text" Then
strWhere = strWhere & "'" & Replace(ctL, "'", "''") & "'"
ElseIf ctL.Tag = "Date" Then
strWhere = strWhere & "#" & ctL & "#"
Else
strWhere = strWhere & ctL
End If
End If
End If
Next
strWhere = Mid(strWhere, 6)
我目前正在实施一个涉及 table 中 30 个字段的重型 WHERE
子句,有没有办法重构:
WHERE (
(table.field1 LIKE "*" & Forms!SearchForm!txt_box1 & "*"
Or Forms!SearchForm!txt_box1 Is Null)
AND (table.field2 LIKE "*" & Forms!SearchForm!txt_box2 & "*"
Or Forms!SearchForm!txt_box2 Is Null)
AND ...
依此类推,直到我到达最后一个字段 (31)。关于如何在这里实现 DRY 方法的任何想法?
我通常做的是将每个控件命名为与要包含在过滤器中的字段相同的名称,并将标记 属性 设置为数据类型。然后遍历控件。
Dim ctL As Access.Control
Dim strWhere As String
For Each ctL In Me.Controls
If ctL.ControlType = acTextBox Or ctL.ControlType = acComboBox Then
If Nz(ctL,"") <> "" Then
strWhere = strWhere & " AND " & ctL.Name & "="
If ctL.Tag = "Text" Then
strWhere = strWhere & "'" & Replace(ctL, "'", "''") & "'"
ElseIf ctL.Tag = "Date" Then
strWhere = strWhere & "#" & ctL & "#"
Else
strWhere = strWhere & ctL
End If
End If
End If
Next
strWhere = Mid(strWhere, 6)