會員登錄 - 用戶注冊 - 網(wǎng)站地圖 Office中國(office-cn.net),專業(yè)Office論壇
當前位置:主頁 > 技巧 > Access技巧 > 模塊函數(shù)VBA > 正文

一個常用的組合多條件查詢 WHERE 子句的函數(shù)

時間:2005-02-06 00:00 來源:Access911 作者:cg1『文章… 閱讀:

 

方法一:

 
本方法編寫了幾個函數(shù)來完成上述工作

 

 

Option Compare Database
'先定義幾個枚舉常量
Public Enum ValueTypeEnum
    vDate = 1
    vString = 2
    vNumber = 3
End Enum
Public Enum OperatorEnum
    vLessThan = 0
    vMorethan = 1
    vEqual = 2
    vLike = 3
End Enum

 

Function JoinWhere(ByVal strFieldName As String, _
                    ByVal varValue As Variant, _
                    Optional ByVal strValueType As ValueTypeEnum = 2, _
                    Optional ByVal intOperator As OperatorEnum = 3) As String
                    

'作者           :cg1
'說明:
'JoinWhere 函數(shù)專門用于組合常用的多條件搜索的Where子句
'參數(shù)說明:
'   strFieldName   :用于傳入需要查詢的字段名
'   varValue       :用于傳入窗體上對應控件的值,可能是 NULL
'   strValueType   :可選參數(shù),用于指定數(shù)據(jù)類型,默認為 string
'   intOperator    :可選參數(shù),用于指定操作符類型,默認為 like


    Dim strOperateor As String
    Select Case intOperator
    Case 0
        strOperator = " <= "
    Case 1
        strOperator = " >= "
    Case 2
        strOperator = " = "
    Case 3
        strOperator = " Like "
    Case Else
        strOperator = " Like "
    End Select
    
    Select Case strValueType
    Case 1  'date
        If IsNull(varValue) = False Then
            If IsDate(varValue) = True Then
                JoinWhere = " (" & strFieldName & strOperator & " #" & CheckSQLWords(CStr(varValue)) & "#) and "
            Else
                MsgBox "“" & CStr(varValue) & "”不是有效的日期,請再次復核!", vbExclamation, "查詢參數(shù)錯誤..."
            End If
        End If
    Case 2  'string
        If IsNull(varValue) = False Then
            JoinWhere = " (" & strFieldName & strOperator & " '*" & CheckSQLWords(CStr(varValue)) & "*') and "
        End If
    Case 3  'number
        If IsNull(varValue) = False Then
            If IsNumeric(varValue) Then
                JoinWhere = " (" & strFieldName & strOperator & CheckSQLWords(CStr(varValue)) & ") and "
            Else
                MsgBox "“" & CStr(varValue) & "”不是正確的數(shù)值,請再次復核!", vbExclamation, "查詢參數(shù)錯誤..."
            End If
        End If
    Case Else
        JoinWhere = ""
    End Select
End Function
Public Function CheckSQLWords(ByVal strSQL As String) As String
'檢查 SQL 字符串中是否包含非法字符
    If IsNull(strSQL) Then
        CheckSQLWords = ""
        Exit Function
    End If
    CheckSQLWords = Replace(strSQL, "'", "''")
End Function

Public Function CheckWhere(ByVal strSQLWhere As String) As String
'用于判斷最終結果是否有 WHERE 子句,因為有可能是不需要條件,查詢出所有的結果集合
    If IsNull(strSQLWhere) = True Then
        Exit Function
    End If
    If strSQLWhere <> "" Then
        strSQLWhere = " where " & strSQLWhere
    End If
    If Right(strSQLWhere, 5) = " and " Then
        strSQLWhere = Mid(strSQLWhere, 1, Len(strSQLWhere) - 5)
    End If
    CheckWhere = strSQLWhere
End Function

Function CheckSQLRight(ByVal strSQL As String) As Boolean
'用 EXECUTE 執(zhí)行一遍來檢測 SQL 是否有錯誤,只適用于耗時較少的 SELECT 查詢
    On Error Resume Next
    CurrentProject.Connection.Execute strSQL
    If Err <> 0 Then
        Debug.Print Err.Number & " -> " & Err.Description
        CheckSQLRight = False
        Exit Function
    End If
    CheckSQLRight = True
End Function


 


實際使用時如下:

 

Private Sub Command12_Click()
    Dim strSQL As String
    Dim strWhere As String
    
    strSQL = "select * " & _
             "FROM tbl_user"
    
    '注意,查 FirstName 的時候并沒有使用后面的兩個參數(shù),
    '因為那兩個參數(shù)是默認值,默認為字符串按LIKE 查詢

    strWhere = JoinWhere("id", Me.id, vNumber, vEqual) & _
                JoinWhere("FirstName", Me.FirstName) & _
                JoinWhere("createdate", Me.CreateDate1, vDate, vMorethan) & _
                JoinWhere("createdate", Me.CreateDate2, vDate, vLessThan) & _
                JoinWhere("worknumber", Me.WorkNumber1, vNumber, vMorethan) & _
                JoinWhere("worknumber", Me.WorkNumber2, vNumber, vLessThan)
    '你無需關心JoinWhere函數(shù)是如何編寫出來的。你只要關心JoinWhere有4個
    '參數(shù),該如何填寫即可。記得組織完 WHERE 子句后用 CheckWhere 函數(shù)檢查一遍。

                
    '以下用于判斷最終結果是否有 WHERE 子句,因為有可能是不需要條件,查詢出所有的結果集合
    strWhere = CheckWhere(strWhere)
    
    strSQL = strSQL & strWhere
    
   
    '以下部分用于檢測 SQL 語句語法是否有錯誤,覺得沒必要可以去掉
    If CheckSQLRight(strSQL) = False Then
        MsgBox "SQL 語句有錯誤,請查看“立即窗口”"
        Exit Sub
    End If
        
    Me.Sub_Frm_UserList.Form.RecordSource = strSQL
End Sub

 

 

 

方法二:
 

 

 

以下將上述幾個函數(shù)寫成了一個類模塊,供大家參考:

Option Compare Database

 

'-----------------------------------------------------
'類模塊名   :clsWhere
'建立方法   :VBE 界面 -> 菜單 -> 插入 -> 類模塊
'作用       :根據(jù)界面輸入,動態(tài)組織 SQL 語句的 Where 子句
'作者       :cg1
'-----------------------------------------------------


'先定義幾個枚舉常量
Public Enum ValueTypeEnum
    vDate = 1
    vString = 2
    vNumber = 3
End Enum
Public Enum OperatorEnum
    vLessThan = 0
    vMorethan = 1
    vEqual = 2
    vLike = 3
End Enum
Private strSQLWhere As String
Private strErrorDescription As String

Public Property Get ErrorDescription() As String
    ErrorDescription = strErrorDescription
End Property

Public Property Get WhereWords() As String
'用于判斷最終結果是否有 WHERE 子句,因為有可能是不需要條件,查詢出所有的結果集合
    Dim strOutput As String
    
    If strErrorDescription <> "" Then
        Debug.Print strErrorDescription
        WhereWords = ""
        Exit Property
    End If
    If IsNull(strOutput) = True Then
        WhereWords = ""
        Exit Property
    Else
        strOutput = strSQLWhere
    End If
    
    If strOutput <> "" Then
        strOutput = " where " & strOutput
    End If
    If Right(strOutput, 5) = " and " Then
        strOutput = Mid(strOutput, 1, Len(strOutput) - 5)
    End If
    WhereWords = strOutput
End Property

Public Function JoinWhere(ByVal strFieldName As String, _
                    ByVal varValue As Variant, _
                    Optional ByVal strValueType As ValueTypeEnum = 2, _
                    Optional ByVal intOperator As OperatorEnum = 3, _
                    Optional ByVal strAlertName As String = "")
                    
'出處           :http://access911.net
'作者           :cg1
'說明:
'JoinWhere 函數(shù)專門用于組合常用的多條件搜索的Where子句
'參數(shù)說明:
'   strFieldName   :用于傳入需要查詢的字段名
'   varValue       :用于傳入窗體上對應控件的值,可能是 NULL
'   strValueType   :可選參數(shù),用于指定數(shù)據(jù)類型,默認為 string
'   intOperator    :可選參數(shù),用于指定操作符類型,默認為 like
'   strAlertName   :可選參數(shù),如果有錯誤,提示用戶是哪個項目出錯了,默認為 ""


    Dim strOperateor As String
    Select Case intOperator
    Case 0
        strOperator = " <= "
    Case 1
        strOperator = " >= "
    Case 2
        strOperator = " = "
    Case 3
        strOperator = " Like "
    Case Else
        strOperator = " Like "
    End Select
    
    Select Case strValueType
    Case 1  'date
        If IsNull(varValue) = False Then
            If IsDate(varValue) = True Then
                JoinWhere = " (" & strFieldName & strOperator & " #" & CheckSQLWords(CStr(varValue)) & "#) and "
            Else
                strErrorDescription = strErrorDescription & "您" & IIf(strAlertName = "", "", "在“" & strAlertName & "”中") & "填寫的“" & CStr(varValue) & "”不是有效的日期,請再次復核!" & vbCrLf
            End If
        End If
    Case 2  'string
        If IsNull(varValue) = False Then
            JoinWhere = " (" & strFieldName & strOperator & " '*" & CheckSQLWords(CStr(varValue)) & "*') and "
        End If
    Case 3  'number
        If IsNull(varValue) = False Then
            If IsNumeric(varValue) Then
                JoinWhere = " (" & strFieldName & strOperator & CheckSQLWords(CStr(varValue)) & ") and "
            Else
                strErrorDescription = strErrorDescription & "您" & IIf(strAlertName = "", "", "在“" & strAlertName & "”中") & "填寫的“" & CStr(varValue) & "”不是正確的數(shù)值,請再次復核!" & vbCrLf
            End If
        End If
    Case Else
        JoinWhere = ""
    End Select
    
    strSQLWhere = strSQLWhere & JoinWhere
    
End Function

Private Function CheckSQLWords(ByVal strSQL As String) As String
'檢查 SQL 字符串中是否包含非法字符
    If IsNull(strSQL) Then
        CheckSQLWords = ""
        Exit Function
    End If
    CheckSQLWords = Replace(strSQL, "'", "''")
End Function

Public Function CheckSQLRight(ByVal strSQL As String) As Boolean
'用 EXECUTE 執(zhí)行一遍來檢測 SQL 是否有錯誤,只適用于耗時較少的 SELECT 查詢
    On Error Resume Next
    CurrentProject.Connection.Execute strSQL
    If Err <> 0 Then
        Debug.Print Err.Number & " -> " & Err.Description
        CheckSQLRight = False
        Exit Function
    End If
    CheckSQLRight = True
End Function


 

調用時代碼如下:

 

Private Sub Command12_Click()
    Dim strSQL As String
    Dim c As New clsWhere
   
    strSQL = "select * " & _
             "FROM tbl_user"
    
    '注意,查 FirstName 的時候并沒有使用后面的兩個參數(shù),
    '因為那兩個參數(shù)是默認值,默認為字符串按LIKE 查詢。
    '注意,參數(shù)“strAlertName”并不一定要等于參數(shù)“varValue”的控件名

    
    With c
        .JoinWhere "id", Me.id, vNumber, vEqual, "id"
        .JoinWhere "FirstName", Me.FirstName, , , "FirstName"
        .JoinWhere "createdate", Me.CreateDate1, vDate, vMorethan, "From CreateDate"
        .JoinWhere "createdate", Me.CreateDate2, vDate, vLessThan, "To CreateDate"
        .JoinWhere "worknumber", Me.WorkNumber1, vNumber, vMorethan, "From WorkNumber"
        .JoinWhere "worknumber", Me.WorkNumber2, vNumber, vLessThan, "To WorkNumber"
    End With
    
    If c.ErrorDescription = "" Then
        Debug.Print c.WhereWords
        '以下部分用于檢測 SQL 語句語法是否有錯誤,覺得沒必要可以去掉
        'If c.CheckSQLRight(strSQL) = False Then
        '    MsgBox "SQL 語句有錯誤,請查看“立即窗口”"
        '    Exit Sub
        'End If

        Me.Sub_Frm_UserList.Form.RecordSource = strSQL & c.WhereWords
    Else
        MsgBox c.ErrorDescription, vbExclamation
        Exit Sub
    End If
    Set c = Nothing
End Sub

 

 

 

示例下載:
http://access911.net/down/eg/eg_query_property.rar (35KB)

(責任編輯:admin)

頂一下
(2)
100%
踩一下
(0)
0%
發(fā)表評論
請自覺遵守互聯(lián)網(wǎng)相關的政策法規(guī),嚴禁發(fā)布色情、暴力、反動的言論。
評價: