设计一个程序,用户从界面选择查询条件,然后得出结果。如果用户不选任何条件,直接查询,则不做响应。
我写了一组sql语句:
strdb= "select * from mytable where"
然后根据用户的选择加上
strdb = strdb & " a = " & a1 & " and "
...
但是我做判断时,下面语句没有设想的结果
if Lcase(Right(strdb,5)) = "where" Then Exit Sub
或者
if Right(strdb,5) = "where" Then Exit Sub请各位帮我检查一下,该怎么写

解决方案 »

  1.   

    '换个思路
    dim where_temp1  as string
    dim where_temp2  as string
    dim strsql as stringif 条件变量1="" then
        where_temp1=""
    else 
        where_temp1=" and 字段1='"& 条件变量1 &"'"
    end if
    if 条件变量2="" then
        where_temp2=""
    else
        where_temp2=" and 字段2='"& 条件变量2 &"'"
    end if'构造SQL查询语句
    strsql=" select * from 表名 where 1=1 " & where_temp1 & where_temp2
      

  2.   

    可以将你所有的条件值定一个变量设一初始值, 如果用户有选择到的话就改变, 最后你判断你的初始值有没有改变,就可以写出相应的SQL语句了。
      

  3.   

    我在判断前用
    debug .print strdb
    确认strdb为
    select * from mytable where 但是我做判断时,下面语句没有设想的结果 
    if Lcase(Right(strdb,5)) = "where" Then Exit Sub 
    那么上面这句有什么不对吗
      

  4.   

    debug .print Lcase(Right(strdb,5))
      

  5.   

    where 1=1 是什么意思啊,能否说的详细些
      

  6.   

    a如果是字符串,那麼,就應該改為:
            strdb = strdb & " a = '" & a1 & "' and " 
    關鍵是看你的a,是什麼類型
      

  7.   

    如果每个条件都是用相同的逻辑运算符连接,这样写也比较简单。Private Sub Command1_Click()
        
        Dim lCount      As Long
        Dim sSql        As String
        Dim vFilters()  As String
        
        ' 按照全部条件数来定义
        ReDim vFilters(1 To max_conditions)
        
        If 选择条件1 Then
            lCount = lCount + 1
            vFilters(lCount) = "字段1 = ..."
        End If
        
        If 选择条件2 Then
            lCount = lCount + 1
            vFilters(lCount) = "字段2 = ..."
        End If
        
        '...
        
        If 选择条件n Then
            lCount = lCount + 1
            vFilters(lCount) = "字段n = ..."
        End If
        
        sSql = "select * from xxx "
        
        If lCount > 0 Then
            
            ReDim Preserve vFilters(1 To lCount)
            
            sSql = sSql & " where " & Join(vFilters, " and ")   ' 也可以用 Or 
            
        End If
        
        MsgBox sSql
        
    End Sub