【问题标题】:SQL Query in VB.NetVB.Net 中的 SQL 查询
【发布时间】:2012-12-18 10:17:43
【问题描述】:

我有一个从数据库中选择 value=combobox.selectedtext 的查询。

但是,我想做的是让 where 值检查组合框的所有值。

有人可以就如何做到这一点提供建议吗?

我现在的sql查询是这样的:

Dim sqlOpServ As String = ("SELECT DISTINCT col1, col2 from table1, table2 where test=test1 AND value= '" & combobox1.SelectedItem & "' ORDER BY col1 ASC")

谢谢

【问题讨论】:

    标签: vb.net visual-studio tsql sql-server-ce


    【解决方案1】:

    我不知道VS,所以我会尝试帮助你而不用尝试我的代码:

     Dim sWhere as string=""
     For i = 0 To ComboBox1.Items.Count - 1
            sSelect = sSelect & " AND value='" & ComboBox1.Items(i) & "' "
     Next
    
     Dim sqlOpServ As String = ("SELECT DISTINCT col1, col2 from table1, table2 where test=test1 " & sWhere & " ORDER BY col1 ASC")
    

    在 cmets 之后:

       Dim sWhere As String = ""
    
        For i = 0 To ComboBox1.Items.Count - 1
            If i = 0 Then
                sWhere = " AND value='" & ComboBox1.Items(i).ToString & "' "
            Else
                sWhere = sWhere & " OR value='" & ComboBox1.Items(i).ToString & "' "
            End If
    
        Next
    
        Dim sqlOpServ As String = _
            ("SELECT DISTINCT col1, col2 from table1, table2 where test=test1 " & sWhere & " ORDER BY col1 ASC")
    

    如果您使用数据表来填充组合框

        Dim table As DataTable = DirectCast(Me.ComboBox1.DataSource, DataTable)
        Dim sWhere As String = ""
    
        For i = 0 To ComboBox1.Items.Count - 1
            Dim displayItem As String = table.Rows(i)(ComboBox1.DisplayMember).ToString()
            ' Dim valueItem As String = table.Rows(i)(ComboBox1.ValueMember).ToString() 'if you need at some point the value you can use this
    
            If i = 0 Then
                sWhere = " AND value='" & displayItem & "' "
            Else
                sWhere = sWhere & " OR value='" & displayItem & "' "
            End If
    
        Next
    
        Dim sqlOpServ As String = _
            ("SELECT DISTINCT col1, col2 from table1, table2 where test=test1 " & sWhere & " ORDER BY col1 ASC")
    

    希望能帮到你

    【讨论】:

    • 这不会像你所说的那样返回任何东西AND ColumnName = 'VALUE1' AND ColumnName = 'VALUE2' 等等。它不能同时有 2 个值。您需要将其括起来并放入ColumnName = 'VALUE1' OR etc...
    【解决方案2】:

    2 种方法

    1)您可以制作所有组合框项的值并用特殊字符分隔,您可以将存储过程中的所有值拆分并得到结果

    2) 您可以创建一个以“或”分隔的字符串,即 value=22 或 value=25,然后您可以执行这些值。

    【讨论】:

      猜你喜欢
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      相关资源
      最近更新 更多