Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Michlos

Fazendo Paginação com tabelas relacionadas

Recommended Posts

Buenas...

A história vai ser longa http://forum.imasters.com.br/public/style_emoticons/default/dormindo.gif

Eu já postei algo parecido sobre esse mesmo problema que, a princípio, estava resolvido...

Era sobre os comando LEFT OUTER JOIN / INNER JOIN / e RIGHT OUTER JOIN isso eu consegui aprender com a ajuda do Jonathan... mas a parada é a seguinte.. o negócio de usar o JOIN não resolveu meus problemas pq não consegui agrupar as informações como eu queria, então eu preferi usar WHERE pegando uma variável de URL para as duas. funcionou.

Tenho uma tabela (REPRESENTANTE) e outra (EMPRESA) que tem vários registros para a primeira ou nenhum..

Fiz tudo e está rodando direitinho.. mas a questão é como fazer uma paginação navegando entre os registros dos REPRESENTANTES sendo que os dois RS usam uma mesma variável de URL (reg)

Tentei usar o paginador do DreamWeaver e ele não funciona, talvez seja por causa da variável de URL.

 

Eu fiz o seguinte:

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1250"%><!--#include virtual="/gestao/Connections/connection.asp" --><%'PEGANDO VARIÁVEL PARA TABELA REPRESENTANTEDim rs__MMColParamrs__MMColParam = "1"If (Request.QueryString("reg") <> "") Then   rs__MMColParam = Request.QueryString("reg")End If%><%'CONEXÃO COM TABELA REPRESENTANTEDim rsDim rs_numRowsSet rs = Server.CreateObject("ADODB.Recordset")rs.ActiveConnection = MM_connection_STRINGrs.Source = "SELECT * FROM representante WHERE r_registro = " + Replace(rs__MMColParam, "'", "''") + ""rs.CursorType = 0rs.CursorLocation = 2rs.LockType = 1rs.Open()rs_numRows = 0%><%'PEGANDO VARIÁVEL PARA EMPRESA - MESMA VARIÁVEL DA OUTRADim rs2__MMColParamrs2__MMColParam = "1"If (Request.QueryString("reg") <> "") Then   rs2__MMColParam = Request.QueryString("reg")End If%><%'CONECTANDO COM A TABELA REPRESENTANTEDim rs2Dim rs2_numRowsSet rs2 = Server.CreateObject("ADODB.Recordset")rs2.ActiveConnection = MM_connection_STRINGrs2.Source = "SELECT * FROM empresas WHERE reg_representante = " + Replace(rs2__MMColParam, "'", "''") + ""rs2.CursorType = 0rs2.CursorLocation = 2rs2.LockType = 1rs2.Open()rs2_numRows = 0%><%'VARIÁVEIS P/ MÚLTIPLOS VALORES DA TABELA EMPRESA CRIADO PELO DREAMWEAVER TAH FUNFANDODim Repeat1__numRowsDim Repeat1__indexRepeat1__numRows = -1Repeat1__index = 0rs2_numRows = rs2_numRows + Repeat1__numRows%><%'MESMA FUNÇÃO ANTERIOR PARA A TABELA REPRESENTANTEDim Repeat2__numRowsDim Repeat2__indexRepeat2__numRows = 1Repeat2__index = 0rs_numRows = rs_numRows + Repeat2__numRows%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1250"><title>Untitled Document</title></head><body><% 'CRIEI ESSE LOOP PARA EU PODER PAGINAR OS REGISTROS FICAM UM EM CADA PÁGINAWhile ((Repeat2__numRows <> 0) AND (NOT rs.EOF)) %><p>Registro:   <%=(rs.Fields.Item("r_registro").Value)%></p><p>Nome: <%=(rs.Fields.Item("r_nome").Value)%></p><p>Empresas</p><% 'USEI DO WHILE AO INVÉS DE SOMENTE WHILE PQ DAVA UM ALERTA NO DW QUE EU NÃO PODERIA USAR UMA WHILE DENTRO DE OUTRA'ESSE LOOP É PARA MOSTRAR OS REGISTROS DAS EMPRESAS DO REPRESENTANTEDo While ((Repeat1__numRows <> 0) AND (NOT rs2.EOF)) %>  <p><%=(rs2.Fields.Item("emp_nome").Value)%></p>  <%   Repeat1__index=Repeat1__index+1  Repeat1__numRows=Repeat1__numRows-1  rs2.MoveNext()Loop%>	<%   Repeat2__index=Repeat2__index+1  Repeat2__numRows=Repeat2__numRows-1  rs.MoveNext()Wend%><p> </p></body></html><%rs.Close()Set rs = Nothing%><%rs2.Close()Set rs2 = Nothing%>
Alguém pode me ajudar em um navegador entre os registros (REPRESENTANTE)?

talves eu tenha feito algo errado em colocar um loop em REPRESENTANTE .. não sei como resolver isso

Eu decidi em parar de tentar usar JOIN para trazer mais de um registro em uma página pq não estava agrupando.

O JOIN estava trazendo tipo assim:

Representante 01

Empresa 01

Representante 01

Empresa 02

por isso não usei pq nao sabia como sair dessa.

Agora eu quero só navegar entre cada registro...

Me salvem ae galera... to cansado de quebrar cabeça com esse troço. Acho que falei de mais e expliquei de menos

Compartilhar este post


Link para o post
Compartilhar em outros sites

Resolvi o problema...

Eu estou usando os comandos prontos do DreamWeaver para facilitar a minha vida mas como sempre a gente tem que mexer uns pausinhos pra poder melhorar pq esse programa é muito mais burro do que a gente pensa...

Coloque a navegação entre registros do proprio DW e tirei o Request.QueryString("reg") da conexão com o banco.

agora ele traz o primeiro registro e está navegando na trankila.

Teve outra coisa que fiz tbm que foi mudar o local onde é feita a RS com a tabela EMRPESA, com isso ele já me traz (dentro do loop de REPRESENTANTE) o valor do registro atual de REPRESENTANTE.

Assim, ao invés de pegar a querystring da URL eu já coloquei o valor do registro em uma variável que o próprio DW criou.

Ficou dessa forma:

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1250"%><!--#include virtual="/gestao/Connections/connection.asp" --><%Dim rsDim rs_numRowsSet rs = Server.CreateObject("ADODB.Recordset")rs.ActiveConnection = MM_connection_STRINGrs.Source = "SELECT * FROM REPRESENTANTE"rs.CursorType = 0rs.CursorLocation = 2rs.LockType = 1rs.Open()rs_numRows = 0%><%'VARIÁVEIS PARA LOOP DE EMPRESASDim Repeat1__numRowsDim Repeat1__indexRepeat1__numRows = -1Repeat1__index = 0rs2_numRows = rs2_numRows + Repeat1__numRows%><%'VARIÁVEIS PARA LOOP DE REPRESENTANTE'ELE TRAZ UM POR ÁGINADim Repeat2__numRowsDim Repeat2__indexRepeat2__numRows = 1Repeat2__index = 0rs_numRows = rs_numRows + Repeat2__numRows%><%'  *** Recordset Stats, Move To Record, and Go To Record: declare stats variables'ISSO TUDO (VAI ATÉ O HEAD) , QUE NEM VOU TENTAR DESVENDAR AGORA, O DW CRIOU PARA NAVEGAÇÃO ENTRE OS REGISTROS'ELE USA INDEX NUM SEI O QUE TEM QUE TER TEMMPO PRA DESVENDAR ESSE TROÇO NEM VOU ME ARRISCARDim rs_totalDim rs_firstDim rs_last' set the record countrs_total = rs.RecordCount' set the number of rows displayed on this pageIf (rs_numRows < 0) Then  rs_numRows = rs_totalElseif (rs_numRows = 0) Then  rs_numRows = 1End If' set the first and last displayed recordrs_first = 1rs_last  = rs_first + rs_numRows - 1' if we have the correct record count, check the other statsIf (rs_total <> -1) Then  If (rs_first > rs_total) Then	rs_first = rs_total  End If  If (rs_last > rs_total) Then	rs_last = rs_total  End If  If (rs_numRows > rs_total) Then	rs_numRows = rs_total  End IfEnd If%><%Dim MM_paramName %><%' *** Move To Record and Go To Record: declare variablesDim MM_rsDim MM_rsCountDim MM_sizeDim MM_uniqueColDim MM_offsetDim MM_atTotalDim MM_paramIsDefinedDim MM_paramDim MM_indexSet MM_rs	= rsMM_rsCount   = rs_totalMM_size	  = rs_numRowsMM_uniqueCol = ""MM_paramName = ""MM_offset = 0MM_atTotal = falseMM_paramIsDefined = falseIf (MM_paramName <> "") Then  MM_paramIsDefined = (Request.QueryString(MM_paramName) <> "")End If%><%' *** Move To Record: handle 'index' or 'offset' parameterif (Not MM_paramIsDefined And MM_rsCount <> 0) then  ' use index parameter if defined, otherwise use offset parameter  MM_param = Request.QueryString("index")  If (MM_param = "") Then	MM_param = Request.QueryString("offset")  End If  If (MM_param <> "") Then	MM_offset = Int(MM_param)  End If  ' if we have a record count, check if we are past the end of the recordset  If (MM_rsCount <> -1) Then	If (MM_offset >= MM_rsCount Or MM_offset = -1) Then  ' past end or move last	  If ((MM_rsCount Mod MM_size) > 0) Then		 ' last page not a full repeat region		MM_offset = MM_rsCount - (MM_rsCount Mod MM_size)	  Else		MM_offset = MM_rsCount - MM_size	  End If	End If  End If  ' move the cursor to the selected record  MM_index = 0  While ((Not MM_rs.EOF) And (MM_index < MM_offset Or MM_offset = -1))	MM_rs.MoveNext	MM_index = MM_index + 1  Wend  If (MM_rs.EOF) Then 	MM_offset = MM_index  ' set MM_offset to the last possible record  End IfEnd If%><%' *** Move To Record: if we dont know the record count, check the display rangeIf (MM_rsCount = -1) Then  ' walk to the end of the display range for this page  MM_index = MM_offset  While (Not MM_rs.EOF And (MM_size < 0 Or MM_index < MM_offset + MM_size))	MM_rs.MoveNext	MM_index = MM_index + 1  Wend  ' if we walked off the end of the recordset, set MM_rsCount and MM_size  If (MM_rs.EOF) Then	MM_rsCount = MM_index	If (MM_size < 0 Or MM_size > MM_rsCount) Then	  MM_size = MM_rsCount	End If  End If  ' if we walked off the end, set the offset based on page size  If (MM_rs.EOF And Not MM_paramIsDefined) Then	If (MM_offset > MM_rsCount - MM_size Or MM_offset = -1) Then	  If ((MM_rsCount Mod MM_size) > 0) Then		MM_offset = MM_rsCount - (MM_rsCount Mod MM_size)	  Else		MM_offset = MM_rsCount - MM_size	  End If	End If  End If  ' reset the cursor to the beginning  If (MM_rs.CursorType > 0) Then	MM_rs.MoveFirst  Else	MM_rs.Requery  End If  ' move the cursor to the selected record  MM_index = 0  While (Not MM_rs.EOF And MM_index < MM_offset)	MM_rs.MoveNext	MM_index = MM_index + 1  WendEnd If%><%' *** Move To Record: update recordset stats' set the first and last displayed recordrs_first = MM_offset + 1rs_last  = MM_offset + MM_sizeIf (MM_rsCount <> -1) Then  If (rs_first > MM_rsCount) Then	rs_first = MM_rsCount  End If  If (rs_last > MM_rsCount) Then	rs_last = MM_rsCount  End IfEnd If' set the boolean used by hide region to check if we are on the last recordMM_atTotal = (MM_rsCount <> -1 And MM_offset + MM_size >= MM_rsCount)%><%' *** Go To Record and Move To Record: create strings for maintaining URL and Form parametersDim MM_keepNoneDim MM_keepURLDim MM_keepFormDim MM_keepBothDim MM_removeListDim MM_itemDim MM_nextItem' create the list of parameters which should not be maintainedMM_removeList = "&index="If (MM_paramName <> "") Then  MM_removeList = MM_removeList & "&" & MM_paramName & "="End IfMM_keepURL=""MM_keepForm=""MM_keepBoth=""MM_keepNone=""' add the URL parameters to the MM_keepURL stringFor Each MM_item In Request.QueryString  MM_nextItem = "&" & MM_item & "="  If (InStr(1,MM_removeList,MM_nextItem,1) = 0) Then	MM_keepURL = MM_keepURL & MM_nextItem & Server.URLencode(Request.QueryString(MM_item))  End IfNext' add the Form variables to the MM_keepForm stringFor Each MM_item In Request.Form  MM_nextItem = "&" & MM_item & "="  If (InStr(1,MM_removeList,MM_nextItem,1) = 0) Then	MM_keepForm = MM_keepForm & MM_nextItem & Server.URLencode(Request.Form(MM_item))  End IfNext' create the Form + URL string and remove the intial '&' from each of the stringsMM_keepBoth = MM_keepURL & MM_keepFormIf (MM_keepBoth <> "") Then   MM_keepBoth = Right(MM_keepBoth, Len(MM_keepBoth) - 1)End IfIf (MM_keepURL <> "")  Then  MM_keepURL  = Right(MM_keepURL, Len(MM_keepURL) - 1)End IfIf (MM_keepForm <> "") Then  MM_keepForm = Right(MM_keepForm, Len(MM_keepForm) - 1)End If' a utility function used for adding additional parameters to these stringsFunction MM_joinChar(firstItem)  If (firstItem <> "") Then	MM_joinChar = "&"  Else	MM_joinChar = ""  End IfEnd Function%><%' *** Move To Record: set the strings for the first, last, next, and previous linksDim MM_keepMoveDim MM_moveParamDim MM_moveFirstDim MM_moveLastDim MM_moveNextDim MM_movePrevDim MM_urlStrDim MM_paramListDim MM_paramIndexDim MM_nextParamMM_keepMove = MM_keepBothMM_moveParam = "index"' if the page has a repeated region, remove 'offset' from the maintained parametersIf (MM_size > 1) Then  MM_moveParam = "offset"  If (MM_keepMove <> "") Then	MM_paramList = Split(MM_keepMove, "&")	MM_keepMove = ""	For MM_paramIndex = 0 To UBound(MM_paramList)	  MM_nextParam = Left(MM_paramList(MM_paramIndex), InStr(MM_paramList(MM_paramIndex),"=") - 1)	  If (StrComp(MM_nextParam,MM_moveParam,1) <> 0) Then		MM_keepMove = MM_keepMove & "&" & MM_paramList(MM_paramIndex)	  End If	Next	If (MM_keepMove <> "") Then	  MM_keepMove = Right(MM_keepMove, Len(MM_keepMove) - 1)	End If  End IfEnd If' set the strings for the move to linksIf (MM_keepMove <> "") Then   MM_keepMove = Server.HTMLEncode(MM_keepMove) & "&"End IfMM_urlStr = Request.ServerVariables("URL") & "?" & MM_keepMove & MM_moveParam & "="MM_moveFirst = MM_urlStr & "0"MM_moveLast  = MM_urlStr & "-1"MM_moveNext  = MM_urlStr & CStr(MM_offset + MM_size)If (MM_offset - MM_size < 0) Then  MM_movePrev = MM_urlStr & "0"Else  MM_movePrev = MM_urlStr & CStr(MM_offset - MM_size)End If%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1250"><title>Untitled Document</title></head><body><%'LOOP DE REPRESENTANTES COMEÇA AKIWhile ((Repeat2__numRows <> 0) AND (NOT rs.EOF)) %><p>Registro:   <%=(rs.Fields.Item("r_registro").Value)%></p><p>Nome: <%=(rs.Fields.Item("r_nome").Value)%></p><p>Empresas</p><%'PEGANDO O REGISTRO DO REPRESENTANTE E PASSANDO O VALOR PARA A VARIÁVEL CRIADA PELO DW (rs2__MMColParam)'FIZ ISSO PRA NAO DAR TRABALHO'ELE PEGA O REGISTRO ATUAL DENTRO DO LOOPING DE REPRESENTANTES PARA ABRIR A CONEXAO COM O EMPRESAS'ESSA FOI A PARTE QUE MUDEI'guardando registro de REPRESENTANTEreg = rs("r_registro")Dim rs2__MMColParamIf reg <> "" Then   rs2__MMColParam = regEnd If%><%'AGORA QUE VOU DAR UM SELECT EM EMPRESASDim rs2Dim rs2_numRowsSet rs2 = Server.CreateObject("ADODB.Recordset")rs2.ActiveConnection = MM_connection_STRINGrs2.Source = "SELECT * FROM empresas WHERE reg_painel = " + Replace(rs2__MMColParam, "'", "''") + "" 'essa é a parte que ele pega a variável usando WHERE ao inves de JOIN'não estou mais preocupado com empresa que não tiverem cadastradasrs2.CursorType = 0rs2.CursorLocation = 2rs2.LockType = 1rs2.Open()rs2_numRows = 0%><%'LOOP PARA EMPRESASDo While ((Repeat1__numRows <> 0) AND (NOT rs2.EOF)) %>  <p><%=(rs2.Fields.Item("emp_nome").Value)%></p>  <%   Repeat1__index=Repeat1__index+1  Repeat1__numRows=Repeat1__numRows-1  rs2.MoveNext()Loop'FIM DO LOOP PARA EMPRESAS%>  <%   Repeat2__index=Repeat2__index+1  Repeat2__numRows=Repeat2__numRows-1  rs.MoveNext()Wend'FIM DO LOOP PARA REPRESENTANTES'AGORA TAH FUNFANDO DE COM FORÇA'ABAIXO SÃO OS BOTÕES DE NAVEGAÇÃO ENTRE OS REGISTROS%><p> </p><table border="0" width="50%" align="center">  <tr>	<td width="23%" align="center"><% If MM_offset <> 0 Then %>		<a href="<%=MM_moveFirst%>"><img src="First.gif" border=0></a>		<% End If ' end MM_offset <> 0 %>	</td>	<td width="31%" align="center"><% If MM_offset <> 0 Then %>		<a href="<%=MM_movePrev%>"><img src="Previous.gif" border=0></a>		<% End If ' end MM_offset <> 0 %>	</td>	<td width="23%" align="center"><% If Not MM_atTotal Then %>		<a href="<%=MM_moveNext%>"><img src="Next.gif" border=0></a>		<% End If ' end Not MM_atTotal %>	</td>	<td width="23%" align="center"><% If Not MM_atTotal Then %>		<a href="<%=MM_moveLast%>"><img src="Last.gif" border=0></a>		<% End If ' end Not MM_atTotal %>	</td>  </tr></table></body></html><%rs.Close()Set rs = Nothing%><%rs2.Close()Set rs2 = Nothing%>
e por aí vai ..

Quem quiser o MDB pra poder é só me mandar um PM que eu mando por e-mail

 

As vezes precisamos só descançar um pouco e dizer não ao stress que as coisas funcionam

Nem precisei quebrar a cabeça pra resolver foi só questão de visão mesmo.

vlw galera...

Compartilhar este post


Link para o post
Compartilhar em outros sites

uma observaçãozinha...

soh pra quem precisar...

 

Para aparecer todos os registros:

Mudar a linha Repeat2__numRows = 1 para

Repeat2__numRows = -1

 

Pra aparecer x registros tipo:

Repeat2__numRows = x

onde x pode ser 2 ou 10 ou 20 ou 5

 

Outro detalhe é com relação ao comando JOIN na conexão.

Se a tabela 2 não tem registro de um item da tabela 1 é só colocar dessa forma:

rs2.Source = "SELECT * FROM empresas RIGHT OUTER JOIN representante ON empresas.reg_representante = representante.r_registro WHERE reg_representante = " + Replace(rs2__MMColParam, "'", "''") + ""
Tipo se você tem na tabela REPRESENTANTE o R_REGISTRO=2 mas não tem o registro correspondente na tabela EMPRESAS em REG_REPRESENTANTE e não colocar dessa forma dá um erro dizendo que não existe registro correpondente.

 

tah funfando que é uma beleza... valeu a pena a ajuda ateh com relação ao INNER JOIN que o Jonathan me passou.

 

VLW VELHINHO!!!

Agora sim, podem fechar esse tópico hehehehe

http://forum.imasters.com.br/public/style_emoticons/default/joia.gif

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.