Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Amigos,
Por favor uma grande ajuda...
Tenho que fazer uma página de busca que traga como resultado uma ou mais condições dentro da Query, e que ainda assim podem variar em até 7 condições.
Não é questão de Inner Join, nem de Union, etc, pois nestes casos eu trago todos os valores.
A idéia é que a busca pode ser feita juntando (Cor, Ano Fabricação, Modelo, Tipo, X, Y, Z) e o usuário pode selecionar de um até sete condições.
A simples idéia de criar combinações para estas condições "manualmente" é inconcebível, e não consegui colocar a variável recuperada como condição na query com o uso de If.
Tipo:
Dim Sql, Rs
Dim cor : cor = request("cor")
Dim modelo : modelo = request("modelo")
Sql = "select cor from tabela where modelo <> "" and cor <> """
Apenas como exemplo, e se a busca não contiver a condição Modelo e tiver uma outra? :huh:
Se eu colocar todas as 7 condições na query a primeira que não for solicitada, dará erro, e por aí vai.
Já pensei e fiz o inner Join e trouxe tudo de uma vez, mas não tive nenhuma idéia de como montar a apresentação do Rs("XYZ ou sei lá o que"), com If's de 7 níveis.
E para ajudar, as informações estão em 4 tabelas diferentes...
Alguém poderia me sugerir um caminho, por favor?
Muitíssimo obrigado!
Alex
Caro Vinícius,
Muitíssimo obrigado por sua resposta exemplificada.
Já realizei pesquisas completas, tanto no fórum como na web e não encontrei muitas alternativas de exemplos.
Até testei alguns deles mas não consegui colocar o If na Query.
A idéia de concatenar se a variável não for vazia é interessante. Vou ver se consigo a sintaxe correta, já que existe o agravante do banco ser Access e serem 4 tabelas.
Mas não tem problema, pelo menos tenho um ponto de apoio.
Valeu mesmo pela ajuda.
Alex
Precisando, estamos ai ;)
olha este exemplo que uso para buscar em um form com opção de "E" "OU" ou palavra "EXATA"
<%
'------------- SEARCH
'******************************************************
'******************************************************
On Error Resume Next
PAGE_SIZE = 20 ' exibir número de resultados
strURL = Request.ServerVariables("URL") ' the URL or Query string
'------------- q = introduzir texto
strSearch = Request.QueryString("q") ' introduzir texto
If strSearch = "" Then
Server.htmlencode(Trim(Request.Form("q")))
End If
strSearch = Replace(strSearch, "'", "''")
'----------- p = RESULTADO PAGING
IF isnumeric(Request.QueryString("p")) = True OR Request.QueryString("p") = "" THEN
If Request.QueryString("p") = "" OR Request.QueryString("p") < 1 Then
iPageCurrent = 1
Else
iPageCurrent = CInt(Request.QueryString("p"))
End If
ELSE
iPageCurrent = 1
END IF
p = iPageCurrent
'----------------- t = SELECIONANDO TABELA
IF isnumeric(Request.QueryString("t")) = True OR Request.QueryString("t") = "" THEN
If Request.QueryString("t") = "" OR Request.QueryString("t") < 1 Then
searchTable = 1 '1
Else
searchTable = 1 'CInt(Request.QueryString("t"))
End If
ELSE
searchTable = 2 '1
END IF
'------------------- m = SEARCH METODO
IF isnumeric(Request.QueryString("m")) = True OR Request.QueryString("m") = "" THEN
' Retrieve m
If Request.QueryString("m") = "" OR Request.QueryString("m") < 1 Then
strMethod = 2
Else
strMethod = CInt(Request.QueryString("m"))
End If
ELSE
strMethod = 2
END IF
'---------------FORM
%>
<form method="get" action="<%= strURL %>">
<p>
<input type="radio" name="m" value="1" <% IF strMethod = 1 THEN response.write "checked=""checked""" END IF%> />
E
<input type="radio" name="m" value="2" <% IF strMethod = 2 OR strMethod = "" THEN response.write "checked=""checked""" END IF%> />
OU
<input type="radio" name="m" value="3" <% IF strMethod = 3 THEN response.write "checked=""checked""" END IF%> />
Exato</p>
<p><input type="text" class="input3" name="q" value="<%= Trim(strSearch) %>" /></p>
<p><input type="submit" value="Procura" />
<br /><br /></p>
</form>
<%
If strSearch <> "" Then
Session("strSearch") = strSearch
IF isnumeric(Request.QueryString("t")) = True OR Request.QueryString("t") = "" THEN
' Retrieve t
If Request.QueryString("t") = "" OR Request.QueryString("t") < 1 Then
searchTable = 1 '1
Else
searchTable = 1 'CInt(Request.QueryString("t"))
End If
ELSE
searchTable = 1' 1
END IF
' TABLES
Select Case searchTable
Case CInt("1")
dbTable = "tMessages"
'strDBPath = Server.MapPath("/blogg/blog.mdb")
Case CInt("2")
'dbTable = "events"
'strDBPath = Server.MapPath("")
Case Else
dbTable = "tMessages"
'strDBPath = Server.MapPath("")
End Select
'------------------ SQL
'SPLIT STRING INTO Arrays
'FOR E AND or CLÁUSULA SQL
IF searchTable = "1" THEN
IF strMethod < 3 THEN
If strMethod = 1 Then
strSplit = Replace(strSearch," "," and ")
Else
strSplit = Replace(strSearch," "," or ")
End If
colTerms = split(strSplit," and ",-1,1)
iUpperTerms = UBound(colTerms)
strWhereClause = ""
'FIELD CLÁUSULA
nr = 0
Do while nr <= 5
nr = nr + 1
searchField = CInt(nr)
Select Case searchField
Case CInt("1")
strTableInClause = "fDate"
Case CInt("2")
strTableInClause = "fHeadline"
Case CInt("3")
strTableInClause = "fMessage"
Case CInt("4")
strTableInClause = "fAuthor"
Case CInt("5")
strTableInClause = "fnota"
'Case Else
End Select
For iLoop = LBound(colTerms) to iUpperTerms
orTerms = split(colTerms(iLoop)," or ",-1,1)
iUpperOrTerms = UBound(orTerms)
strWhereClause = strWhereClause & ""
for iOrLoop = LBound(orTerms) to iUpperOrTerms
strWhereClause = strWhereClause & strTableInClause & " LIKE '%" & Trim(orTerms(iOrLoop)) & "%' "
if iOrLoop < iUpperOrTerms then
strWhereClause = strWhereClause & " OR "
end if
next
strWhereClause = strWhereClause & ""
if iLoop < iUpperTerms then
strWhereClause = strWhereClause & " AND "
end If
Next
if nr <= 4 then
strWhereClause = strWhereClause & " OR "
end if
Loop
ELSE
' METODO 3 FRASE EXATA
strWhereClause = "fDate LIKE '%" & strSearch & "%' OR fHeadline LIKE '%" & strSearch & "%' OR fMessage LIKE '%" & strSearch & "%' OR fAuthor LIKE '%" & strSearch & "%' OR fnota LIKE '%" & strSearch & "%'"
END IF
strWhereClause2 = "WHERE (" & strWhereClause & ") AND (online = CBool(-1))"
' ORDER BY
strOrderClause = "ORDER BY fdate DESC"
IF strMethod = 3 THEN
strSQL = "SELECT * FROM "& dbTable &" "& strWhereClause2 &" "& strOrderClause &";"
ELSE
strSQL = "SELECT * FROM "& dbTable &" "& strWhereClause2 &" "& strOrderClause &";"
END IF
END IF
Response.write strSQL
'---------- END SQL
'--------- CONNECTION OPEN & EXE SQL
Set myRecSet = Server.CreateObject("ADODB.Recordset")
myRecSet.PageSize = PAGE_SIZE
myRecSet.CacheSize = PAGE_SIZE
' constantes
adOpenStatic = 3
adLockReadOnly = 1
adCmdText = &H0001
myRecSet.Open strSQL, sConn, adOpenStatic, adLockReadOnly, adCmdText
iRecordCount = myRecSet.RecordCount
iPageCount = myRecSet.PageCount
' COUNTER
strCountRecord = iRecordCount
If iPageCurrent = 1 Then
strCount = strCountRecord - iRecordCount + 1
Else
strCount = iPageCurrent * PAGE_SIZE - PAGE_SIZE + 1
'strCountRecord - + * iPageCurrent
End If
If iRecordCount = 0 Then
%> <p>Desculpa, sua busca não retornou resultados.<br />
Sua Busca por - <b><%=strSearch%></b> - não retornou documentos.</p>
<%
Else
myRecSet.AbsolutePage = iPageCurrent
If iRecordCount <= PAGE_SIZE then
toRecord = iRecordCount
else
toRecord = strCount + PAGE_SIZE - 1
End if
If toRecord => iRecordCount then
toRecord= iRecordCount
End if
%>
<p>Mostrando resultado <%=strCount%> - <%=toRecord%> de <%=iRecordCount %>. Paginas <%= iPageCurrent %> / <%= iPageCount %>. </p>
<br /><p>
<%
If iPageCurrent > 1 Then
%>
<a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(strSearch) %>&p=<%= iPageCurrent - 1 %>" title="Previous">
‹‹</a>
<%
End If
For I = 1 To iPageCount
If I = iPageCurrent Then
%>
<%= I %>
<%
Else
%>
<a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(strSearch) %>&p=<%= I %>" title="<%= I %>"><%= I %></a>
<%
End If
Next 'I
If iPageCurrent < iPageCount Then
%>
<a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(strSearch) %>&p=<%= iPageCurrent + 1 %>" title="Next"> ››</a>
<%
End If
%></p>
<%
'----------------RESULTADO LOOP
Do While Not myRecSet.EOF And myRecSet.AbsolutePage = iPageCurrent
intNumMatches = 0
allregText = ""
regWriteOut = ""
If strSearch = " " then
strSearch = ""
End if
Set objRegExp = New RegExp
objRegExp.Global = True
objRegExp.IgnoreCase = True
If dbTable = "tMessages" then
allregText = myRecSet.Fields("fDate").Value & " " & myRecSet.Fields("fHeadline").Value & " " & myRecSet.Fields("fMessage").Value & " " & myRecSet.Fields("fAuthor").Value
End If
allregText = Replace(allregText, "<", "", 1, -1, 1)
allregText = Replace(allregText, ">", "", 1, -1, 1)
allregText = UTFtoISO(allregText)
If strMethod = 3 then
'Definir o padrão de pesquisa para
objRegExp.Pattern = strSearch
'Procurar o arquivo para a frase
Set objMatches = objRegExp.Execute(allregText)
'Obter o número de vezes que a frase é compensada intNumMatches = objMatches.Count
End if
If strMethod < 3 then
sarySearchWord = Split(strSearch, " ")
For intSearchLoopCounter = 0 to UBound(sarySearchWord)
'Definir o padrão de pesquisa para
objRegExp.Pattern = "" & sarySearchWord(intSearchLoopCounter) & ""
'Procurar o arquivo para a frase
Set objMatches = objRegExp.Execute(allregText)
intNumMatches = intNumMatches + objMatches.Count
Next
End if
If intNumMatches => 1 Then
If intNumMatches > 1 then
regWriteOut = "" & intNumMatches & " hits."
Else
regWriteOut = "" & intNumMatches & " hit."
End If
End If
Set objRegExp = Nothing
%>
<% IF dbTable = "tMessages" THEN %>
<p><br /><br />
<%=strCount%>. <a href="default.asp?id=<%= myRecSet.Fields("id").Value %>" title="<%=myRecSet.Fields("fHeadline").Value%>"><%= myRecSet.Fields("fHeadline").Value %></a>
<br /><%= RemoveHTML(Left(myRecSet.Fields("fMessage").Value,instrrev(Left(myRecSet.Fields("fMessage").Value,280),"")))%>
<br />
Postado: <%= year(myRecSet.Fields("fdate").Value) & "-" & right("00" & cstr(month(myRecSet.Fields("fdate").Value)),2) & "-" & right("00" & cstr(day(myRecSet.Fields("fdate").Value)),2) & ". " & regWriteOut%>
</p>
<% END IF%>
<%
strCount = strCount + 1
myRecSet.MoveNext
Loop
'----------------RESULTADO LOOP END
%>
<br /><br /><p>
<%
If iPageCurrent > 1 Then
%>
<a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(Session("strSearch")) %>&p=<%= iPageCurrent - 1 %>" title="Previous">‹‹</a>
<%
End If
For I = 1 To iPageCount
If I = iPageCurrent Then
%>
<%= I %>
<%
Else
%>
<a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(Session("strSearch")) %>&p=<%= I %>" title="<%= I %>"><%= I %></a>
<%
End If
Next 'I
If iPageCurrent < iPageCount Then
%>
<a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(Session("strSearch")) %>&p=<%= iPageCurrent + 1 %>" title="Next">››</a>
<%
End If
%>
<%
End If
%></p>' CLOSE
myRecSet.Close
Set myRecSet = Nothing
End If
'---------------- SEARCH END
'******************************************************
'******************************************************
%>
Existem 2 possibilidades ao meu ver:
A primeira seria usar um like em todas as variaveis, talvez com um tratamento se elas estiverem vazias para não gerar erro.
if not data ="" then
sql=sql + data
end if
e assim vai