注册 登录
编程论坛 SQL Server论坛

sql 查询 Text1.Text 输入非空的才拼条件 出现FORM子语法错误

zyangc 发布于 2016-10-30 16:53, 2361 次点击
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sql As String
Dim sqlWhere As String
Private Sub Command1_Click() '查询
    If cn.State = adStateOpen Then cn.Close
    If rs.State = adStateOpen Then rs.Close
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "/db.mdb;Persist Security Info=False"
 sqlWhere = vbNullString
    If Trim(Text1.Text) = "" Then
           sqlWhere  = sqlWhere &  年级 like '" & Combo1.Text & "' and 班级 like '" & Combo2.Text & "'"
    End If
    If Trim(Text1.Text) <> 0 Then
        sqlWhere  = sqlWhere &  年级 like '" & Combo1.Text & "' and 班级 like '" & Combo2.Text & "' and 姓名 like '" & Text1.Text & "'
    End If
 
    sql = "select * from 档案 " & sqlWhere
 
    rs.Open sql, cn, 3, 3 出现FORM子语法错误
3 回复
#2
mywisdom882016-10-31 09:33
你这个是VB的吧?
是拼接完后,输出你拼接的字符串看看,是什么内容。
#3
厨师王德榜2016-11-01 12:34
一段VB 用ADO方式访问Access数据库的代码是吧,需要跟踪一下 变量 sql、sqlWhere,貌似你sqlWhere这个变量里没有字符“ Where ...”
#4
ZHRXJR2016-11-18 18:34
sqlWhere = vbNullString 语句应该有问题,修改为:sqlWhere = " Where "
这样,sql = "select * from 档案 " & sqlWhere 的字符串的值应该是:
sql = "select * from 档案 Where 年级 like '" & Combo1.Text & "' and 班级 like '" & Combo2.Text & "'"
或 sql = "select * from 档案 Where 年级 like '" & Combo1.Text & "' and 班级 like '" & Combo2.Text & "' and 姓名 like '" & Text1.Text & "'"
但你的这个语句也需要修改:
sqlWhere = sqlWhere & "年级 like '" & Combo1.Text & "' and 班级 like '" & Combo2.Text & "'"
sqlWhere = sqlWhere & "年级 like '" & Combo1.Text & "' and 班级 like '" & Combo2.Text & "' and 姓名 like '" & Text1.Text & "'"
注意引号的应用。

If Trim(Text1.Text) = "" Then
    sqlWhere = sqlWhere & "年级 like '" & Combo1.Text & "' and 班级 like '" & Combo2.Text & "'"
Else   '这里就是Trim(Text1.Text) <> "",使用一个判断语句比你使用二个判断语句更不容易出错
    sqlWhere = sqlWhere & "年级 like '" & Combo1.Text & "' and 班级 like '" & Combo2.Text & "' and 姓名 like '" & Text1.Text & "'"
End If

[此贴子已经被作者于2016-11-19 07:40编辑过]

1