asp多条件查询

2025-03-23 02:48:20
推荐回答(5个)
回答1:

你这种写法是错误的:
第一:当names这个参数值为空的时个,你的查询语句就会出错!
第二:asp中的连接符号不是“+” 而是 “&”
综上,你应该将条件查询语句改成这样的

<%
names=Request.Form("names")
address=Request.Form("address")
tel=Request.Form("tel")
qq=Request.Form("qq")
%>









姓名 地址 电话 QQ



<%
set rs=server.CreateObject("adodb.recordset")
sql="select * from info where 1=1"
if names<>"" then
sql=sql & " and names='%"&names&"%' "
end if
if address<>"" then
sql=sql & " and address='%"&address&"%' "
end if
if tel<>"" then
sql=sql & " and tel='%"&tel&"%'"
end if
if qq<>"" then
sql=sql & " and qq like '%"&qq&"%'"
end if
sql=sql & " order by id "

rs.open sql,conn,1,1
Do While Not rs.eof
%>








<%=rs("names")%> <%=rs("address")%> <%=rs("tel")%> <%=rs("qq")%>



<%
rs.movenext
Loop
rs.close
set rs=nothing
set conn=nothing
%>
这样就应该不会有错了!

回答2:

可以在你的“查询”提交后,在原来表一的位置显示表二,那么,这就要求你在显示表一和表二之前,准确告诉页面,你要显示的是什么内容。
我教你个相对简单也好理解的方法:
IF
Request.Form("submit")<>"提交"
Then
SQLStr
=
"Select
*
From
Tablename"'先确定你要显示的表的内容;
Else
SQLStr
=
"Select
*
From
Tablename
Where
名称='"&Request.Form("名称")&"'"
and
.....(这里把从表单获得的条件补充完整,最好在这之前把获得的内容验证一下非空)
End
IF
Conn.Execute(SQLStr)
表格
--------------------------
因为你表一和表二格式一样,所以不用分那么清了,就一个表格就可以了,由于上面已经告诉页面要显示的东西了。换言之,要显示的是表一还是表二,在前面已经告诉页面了。

回答3:

ASP 连接字符串应该用&而不是+。
另外提点意见:
1.这个SQL语句写的如果是所有条件都为空的话,会出错,
所以你可以把第一句的改一下。
sql="select * from info where"
改为
sql="select * from info where 1=1 and "
这样即使全为空也不会出错.
2.查询条件中使用=号时,后面不需要再用%号了.

3.应该把传过来的值用trim把左右空格去掉,不然有空格时查不到你想要的数据.

一点经验.

回答4:

set rs=server.CreateObject("adodb.recordset")
sql="select * from info where 1=1 "'最好就加个1+1,如果下在的条件,没一个是存在的。那这句SQL语句不是会报错啊?
if names<>"" then
sql=sql & " and names like '%"&names&"%' "
end if
if address<>"" then
sql=sql & " and address like '%"&address&"%' "
end if
if tel<>"" then
sql=sql & " and tel like '%"&tel&"%'"
end if
if qq<>"" then
sql=sql & " and qq like '%"&qq&"%'"
end if
sql=sql + " order by id "

回答5:

sql="where
1"if
1
and
2
and
3
and
4
and
5
thensql=sql&"
1
and
2
and
3
and
4
and
5"elseif
1
and
2
thensql=sql&"
1
and
2
"elseif
1
and
3
thensql=sql&"
1
and
3
"elseif
1
and
4
thensql=sql&"
1
and
4
"elseif
1
and
5
thensql=sql&"
1
and
5"elseif
2
and
3
then.......如此判断所有自己要做的情况
end
if