为什么我的SQL语句在使用AND或OR时会以这种方式运行 - Visual Basic

时间:2017-10-23 12:21:48

标签: sql vb.net

我有一个带有两个单选按钮(SSOP或SCOP)的表单,六个复选框和一个组合框。根据单选按钮的选择,组合框将被填充,然后使用复选框进行过滤(可以选择多个复选框)

我已经编写了下面的代码,当我只选择复选框时,它工作正常,只显示该复选框的SSOP。但是当我选择多个复选框时,它会向我显示SSOP和SCOP。好像LIKE语句被绕过了。那是为什么?

由于

    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles 
    btnSearch.Click

 SQLa = "SELECT * FROM ARES_Procedure_List WHERE ARES_ID LIKE '%SSOP%' "
        Dim strChk As String = ""
        Dim chk As CheckBox
        Dim strSubsystem As String = ""
        Dim listSubsystem As List(Of [String]) = New List(Of String)
        For Each ctl As Control In Me.Controls
            If TypeOf ctl Is CheckBox Then
                chk = DirectCast(ctl, CheckBox)
                If chk.Checked = True Then
                    listSubsystem.Add("Subsystem = '" & 
         Microsoft.VisualBasic.Mid(chk.Text, 1) & "'")

                End If
            End If

        Next
        strSubsystem = [String].Join(" OR ", listSubsystem.ToArray())
        Label1.Text = strSubsystem
        SQLa = SQLa & "AND " & strSubsystem & ""
        MsgBox(SQLa)
        CallAccess()
        cboSelect.Items.Clear()
        Do Until RSa.EOF()
        cboSelect.Items.Add(RSa.Fields("ARES_ID").Value)
        RSa.MoveNext()
        Loop
        CloseAccess()
    End Sub

1 个答案:

答案 0 :(得分:1)

强制正确的逻辑运算符评估顺序,在OR条件序列周围添加括号

SQLa = SQLa & "AND (" & strSubsystem & ")"

但是,您应该对复选框的状态添加一些控件。如果没有检查它们,则代码会构建无效的SQL

if listSubsystem.Count > 0 Then
    strSubsystem = [String].Join(" OR ", listSubsystem.ToArray())
    Label1.Text = strSubsystem
    SQLa = SQLa & "AND (" & strSubsystem & ")"
End If

旁注。可以使用

重写和缩短检查循环
    For Each chk In Me.Controls.OfType(Of CheckBox)
        If chk.Checked Then
            listSubsystem.Add("Subsystem = '" & Microsoft.VisualBasic.Mid(chk.Text, 1) & "'")

       End If
    Next

直接在OfType(Of CheckBox)IEnumerable扩展

中完成过滤和转换