Ir para conteúdo
Fórum Script Brasil
  • 0

(Resolvido) Atualizar uma tabela após atualizar outra.


mmousinho

Pergunta

Boa noite pessoal, estou quebrando a cabeça em uma questão aqui faz dois dias, já pesquisei em vários Fóruns e vídeo aulas mais sem sucesso.

O Problema é o Seguinte.

Tenho duas tabelas (contas_a_pagar) e (conta_a_pagar detalhes), em uma delas tenho um atualizo via "FORM" as contas com valores total da mesma, na outra atualizo "Botão Gerar Parcelas" e utilizo para gerar as parcelas.
A Parte 1 que uso para gerar parcelas e inserir na minha tabela "contas_a_pagar_detalhe" esta funcionando normalmente e usei o comando abaixo:
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
procedure Tfrm_ContasAPagar.BitBtn_GerarParcaela_MovClick(Sender: TObject);
var
 qend, qend1 : TZQuery;
 LongintVar, i : Integer;
 DataConta : TDate;
 DataUltParcela : TDate;
begin
 qend := TZQuery.Create(nil);
 qend.Connection := dm.Conect;
 
 qend1 := TZQuery.Create(nil);
 qend1.Connection := dm.Conect;
 
 qend.SQL.Clear;
 qend.SQL.Add(' SELECT ID, CENTRODECUSTO, VALORTOTAL '+#10+
              ' FROM CONTAS_A_PAGAR WHERE ID = '''+
 dm.qContasaPagar.FieldByName('id').asstring +''' ');
 qend.Open;
 
 qend1.SQL.Clear;
 qend1.SQL.Add('SELECT IDCONTA FROM CONTAS_A_PAGAR_DETALHE '+
 'WHERE IDCONTA = '''+ qend.FieldByName('ID').AsString +''' ');
 qend1.Open;
 
   LongintVar := StrToInt(edt_QtdParcelas_CP.Text);
   DataConta := StrToDate(edt_Data_CP.text);
 try
  if LongintVar = 1 then
   begin
     Messagedlg('Este Pagamento não tem Parcelas a Ser Geradas!',mtinformation,[mbok],0);
     exit;
   end
   else
 if qend1.RecordCount > 0 then
  begin
   Messagedlg('As Parcelas Já Foram Geradas Anteriormente!',mtinformation,[mbok],0);
   exit;
  end
  else
  begin
  LongintVar := StrToInt(edt_QtdParcelas_CP.Text);
  for I := 1 to LongintVar do
    begin
     qend1.SQL.Clear;
     qend1.SQL.Add(' INSERT INTO CONTAS_A_PAGAR_DETALHE      '+#10+
                  ' (CENTRODECUSTO, IDCONTA, VALOR, JUROS,   '+#10+
                  '  DESCONTOS, DATAVENCIMENTO, PARCELA, VALORDEVEDOR)     ');
     qend1.SQL.Add(' VALUES                                  ');
     qend1.SQL.Add(' (:P1, :P2, :P3, :P4, :P5, :P6, :P7, :P8)     ');
 
     qend1.ParamByName('P1').asString    :=
                                     qend.FieldByName('CENTRODECUSTO').asString;
 
     qend1.ParamByName('P2').asString    := qend.FieldByName('ID').asString;
 
     qend1.ParamByName('P3').AsCurrency
                           := qend.FieldByName('VALORTOTAL').Value / LongintVar;
 
     qend1.ParamByName('P4').asString    := '0';
     qend1.ParamByName('P5').asString    := '0';
     qend1.ParamByName('P6').asDate      := incMonth(DataConta, i);
     qend1.ParamByName('P7').AsString   := IntToStr(i)+'/'+ IntToStr(LongintVar);
     qend1.ParamByName('P8').AsCurrency
                           := qend.FieldByName('VALORTOTAL').Value / LongintVar;
     qend1.ExecSQL;
     end;
  end;
 
  except
   On E: Exception do
   raise Exception.Create(E.Message);
 
  end;
      ShowMessage('Foram Geradas ' + IntToStr(LongintVar) + ' Parcela(s) com Sucesso');
end;



A Segunda Parte que é para atualizar meu campo "DatavUltParcela" na minha tabela conforme a "contas_a_pagar" é que mora o problema.

Segue o comando que estou usando para ela.
 

1
2
3
4
5
6
7
8
9
begin
      qend.SQL.Clear;
      qend.SQL.Add(' UPDATE CONTAS_A_PAGAR SET  (DATAVULTPARCELA)        '+#10+
      ' WHERE ID = '''+ qend1.FieldByName('IDCONTA').AsString +'''       ');
      qend.SQL.Add(' VALUES                                              ');
      qend.SQL.Add(' (:CP1)                                              ');
      qend.ParamByName('CP1').asDate      := incMonth(DataConta, i);
      qend.ExecSQL;
      end;



Será que estou fazendo algo de errado?

Segue o código Completo do codigo:
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
procedure Tfrm_ContasAPagar.BitBtn_GerarParcaela_MovClick(Sender: TObject);
var
 qend, qend1 : TZQuery;
 LongintVar, i : Integer;
 DataConta : TDate;
 DataUltParcela : TDate;
begin
 qend := TZQuery.Create(nil);
 qend.Connection := dm.Conect;
 
 qend1 := TZQuery.Create(nil);
 qend1.Connection := dm.Conect;
 
 qend.SQL.Clear;
 qend.SQL.Add(' SELECT ID, CENTRODECUSTO, VALORTOTAL '+#10+
              ' FROM CONTAS_A_PAGAR WHERE ID = '''+
 dm.qContasaPagar.FieldByName('id').asstring +''' ');
 qend.Open;
 
 qend1.SQL.Clear;
 qend1.SQL.Add('SELECT IDCONTA FROM CONTAS_A_PAGAR_DETALHE '+
 'WHERE IDCONTA = '''+ qend.FieldByName('ID').AsString +''' ');
 qend1.Open;
 
   LongintVar := StrToInt(edt_QtdParcelas_CP.Text);
   DataConta := StrToDate(edt_Data_CP.text);
 try
  if LongintVar = 1 then
   begin
     Messagedlg('Este Pagamento não tem Parcelas a Ser Geradas!',mtinformation,[mbok],0);
     exit;
   end
   else
 if qend1.RecordCount > 0 then
  begin
   Messagedlg('As Parcelas Já Foram Geradas Anteriormente!',mtinformation,[mbok],0);
   exit;
  end
  else
  begin
  LongintVar := StrToInt(edt_QtdParcelas_CP.Text);
  for I := 1 to LongintVar do
    begin
     qend1.SQL.Clear;
     qend1.SQL.Add(' INSERT INTO CONTAS_A_PAGAR_DETALHE      '+#10+
                  ' (CENTRODECUSTO, IDCONTA, VALOR, JUROS,   '+#10+
                  '  DESCONTOS, DATAVENCIMENTO, PARCELA, VALORDEVEDOR)     ');
     qend1.SQL.Add(' VALUES                                  ');
     qend1.SQL.Add(' (:P1, :P2, :P3, :P4, :P5, :P6, :P7, :P8)     ');
 
     qend1.ParamByName('P1').asString    :=
                                     qend.FieldByName('CENTRODECUSTO').asString;
 
     qend1.ParamByName('P2').asString    := qend.FieldByName('ID').asString;
 
     qend1.ParamByName('P3').AsCurrency
                           := qend.FieldByName('VALORTOTAL').Value / LongintVar;
 
     qend1.ParamByName('P4').asString    := '0';
     qend1.ParamByName('P5').asString    := '0';
     qend1.ParamByName('P6').asDate      := incMonth(DataConta, i);
     qend1.ParamByName('P7').AsString   := IntToStr(i)+'/'+ IntToStr(LongintVar);
     qend1.ParamByName('P8').AsCurrency
                           := qend.FieldByName('VALORTOTAL').Value / LongintVar;
     qend1.ExecSQL;
     end;
 
     begin
      LongintVar := StrToInt(edt_QtdParcelas_CP.Text);
      for I := 1 to LongintVar do
      begin
       qend.SQL.Clear;
       qend.SQL.Add(' UPDATE CONTAS_A_PAGAR SET  (DATAVULTPARCELA)        '+#10+
       ' WHERE ID = '''+ qend1.FieldByName('IDCONTA').AsString +'''       ');
       qend.SQL.Add(' VALUES                                              ');
       qend.SQL.Add(' (:CP1)                                              ');
       qend.ParamByName('CP1').asDate      := incMonth(DataConta, i);
       qend.ExecSQL;
       end;
    end;
 
 
 
  end;
 
  except
   On E: Exception do
   raise Exception.Create(E.Message);
 
  end;
      ShowMessage('Foram Geradas ' + IntToStr(LongintVar) + ' Parcela(s) com Sucesso');
end;



Estou trabalhando com banco de dados Mysql.

Será que estou colocando a segunda parte no lugar errado? Falta algo? ou o Procedimento é errado?

Alguém pode me ajudar por favor?

Estou iniciando meus trabalhos com Delphi Tokio 10.2 e ainda sou um pouco leigo no assunto!!!

Desde já agradeço a todos que ajudarem ou pelo menos tentarem.

Link para o comentário
Compartilhar em outros sites

12 respostass a esta questão

Posts Recomendados

  • 0
 qend.SQL.Clear;
 qend.SQL.Add(' SELECT ID, CENTRODECUSTO, VALORTOTAL '+#10+
              ' FROM CONTAS_A_PAGAR WHERE ID = '''+
 dm.qContasaPagar.FieldByName('id').asstring +''' ');
 qend.Open;
 
 qend1.SQL.Clear;
 qend1.SQL.Add('SELECT IDCONTA FROM CONTAS_A_PAGAR_DETALHE '+
 'WHERE IDCONTA = '''+ qend.FieldByName('ID').AsString +''' ');
 qend1.Open; 

OBS: Verifique se o erro ocorre quando voce abre a tabela...

verifique tambem se o FieldByName('ID') esta correto para as 2 tabelas

O erro de Kernel32 ocorre quando não foi  possivel a conexão com o banco de dados

Use o BreakPoint do Delphi para poder acompanhar o processamento das linhas do programa e verificar exatamente onde o erro ocorre.

abraço

Link para o comentário
Compartilhar em outros sites

  • 0

Amigo, sou meio leigo no delphi ainda por isso não entendi bem o que fazer.

LongintVar2 := StrToInt(edt_QtdParcelas_CP.Text);
     for I2 := 1 to LongintVar do

      qend.SQL.Clear;
      qend.SQL.Add(' UPDATE CONTAS_A_PAGAR ');
      qend.SQL.Add(' SET DATAVULTPARCELA = :CP1 ');
      qend.SQL.Add(' WHERE ID = :IDCONTA ');
      qend.ParamByName('IDCONTA').AsInteger := dm.qparcelasIDConta.Value;
      qend.ParamByName('CP1').AsDate        := incMonth(DataConta, i2);
      qend.ExecSQL;

Mais mudei o código e já verifiquei as tabelas e estão corretas...neste momento não esta dando erro, porém a segunda tabela que é a variável "qend" no campo "DATAVULTPARCELA" não esta atualizando após o processo.

Link para o comentário
Compartilhar em outros sites

  • 0

Para atualizar a Tabela use o comando Refresh.

exemplo:

Tabela.Refresh   ///  onde Tabela e o nome da sua tabela ou do componente de acesso.

Se mesmo assim, não atualizar o valor do campo, então use o comando para salvar os registros da tabela

Exemplo:

CDS_Tabela.Post;

CDS_Tabela.ApplyUpdates(-1);

abraço

 

Link para o comentário
Compartilhar em outros sites

  • 0

voce sabe usar o breakpoint do delphi ?

begin
  •  qend := TZQuery.Create(nil);
      qend.Connection := dm.Conect;

no começo do seu código que esta no botão, clique com o mouse ... vai aparecer uma bolinha  vermelha ( esse é o breakpoint ) 

quando voce executar o seu código, o programa vai parar onde esta esse ponto, e a partir dai voce vai apertar a tecla ( F8 )

então o código irá sendo executado a cada vez que voce teclar o F8 ( linha por linha).

se voce posicionar o mouse nas variaveis, ele ira mostrar o conteudo delas.

dessa maneira voce vai seguindo o processamento e verificando se estão sendo passados os valores que estão sendo esperados pelos parametros.

se houver algum erro, o programa para exatamente na linha onde esta o erro... fica mais facil resolver o problema.

tente ai e veja se consegue resolver

abraço

Link para o comentário
Compartilhar em outros sites

  • 0

eu não gosto de usar ... mas isso vai de cada um

eu prefiro fazer um select para trazer o registro que eu quero, e depois trato individualmente cada campo do registro atribuindo os valores e depois salvando

nunca tive problemas .... tenho tabelas com mais de 200 mil registros

abraço

Link para o comentário
Compartilhar em outros sites

  • 0

Pessoal, consegui resolver aqui!!!

Montei uma SQL para atualizar com um c o campo fantasma que já havia na segunda tabela (DataRecebimento), este campo se tornou a data da ultima parcela com o comando MAX() de  acordo com ID e IDCONTA.

Segue o código: 

 procedure Tfrm_ContasAPagar.BitBtn_GerarParcaela_MovClick(Sender: TObject);
var
 qend, qend1 : TZQuery;
 LongintVar, i : Integer;
 LongintVar2, i2 : Integer;
 DataConta : TDate;
 DataUltParcela : TDate;
begin
 qend := TZQuery.Create(nil);
 qend.Connection := dm.Conect;

 qend1 := TZQuery.Create(nil);
 qend1.Connection := dm.Conect;

 qend.SQL.Clear;
 qend.SQL.Add(' SELECT ID, CENTRODECUSTO, VALORTOTAL '+#10+
              ' FROM CONTAS_A_PAGAR WHERE ID = '''+
 dm.qContasaPagar.FieldByName('id').asstring +''' ');
 qend.Open;

 qend1.SQL.Clear;
 qend1.SQL.Add('SELECT IDCONTA FROM CONTAS_A_PAGAR_DETALHE '+
 'WHERE IDCONTA = '''+ qend.FieldByName('ID').AsString +''' ');
 qend1.Open;

   LongintVar := StrToInt(edt_QtdParcelas_CP.Text);
   DataConta := StrToDate(edt_Data_CP.text);


 try

  if qend1.RecordCount > 0 then
  begin
   Messagedlg('As Parcelas Já Foram Geradas Anteriormente!',mtinformation,[mbok],0);
   exit;
  end
  else
  begin
  LongintVar := StrToInt(edt_QtdParcelas_CP.Text);
  for I := 1 to LongintVar do
    begin
     qend1.SQL.Clear;
     qend1.SQL.Add(' INSERT INTO CONTAS_A_PAGAR_DETALHE      '+#10+
                  ' (CENTRODECUSTO, IDCONTA, VALOR, JUROS,   '+#10+
                  '  DESCONTOS, DATAVENCIMENTO, PARCELA, VALORDEVEDOR)     ');
     qend1.SQL.Add(' VALUES                                  ');
     qend1.SQL.Add(' (:P1, :P2, :P3, :P4, :P5, :P6, :P7, :P8)     ');

     qend1.ParamByName('P1').asString    :=
                                     qend.FieldByName('CENTRODECUSTO').asString;

     qend1.ParamByName('P2').asString    := qend.FieldByName('ID').asString;

     qend1.ParamByName('P3').AsCurrency
                           := qend.FieldByName('VALORTOTAL').Value / LongintVar;

     qend1.ParamByName('P4').asString    := '0';
     qend1.ParamByName('P5').asString    := '0';

     if LongintVar = 1 then
     begin
      qend1.ParamByName('P6').asDate      := DataConta;
     end
     else
     qend1.ParamByName('P6').asDate      := incMonth(DataConta, i-1);
     qend1.ParamByName('P7').AsString   := IntToStr(i)+'/'+ IntToStr(LongintVar);
     qend1.ParamByName('P8').AsCurrency
                           := qend.FieldByName('VALORTOTAL').Value / LongintVar;
     qend1.ExecSQL;
     end;

  end;

  except
   On E: Exception do
   raise Exception.Create(E.Message);

  end;

     if LongintVar = 1 then
   begin
     ShowMessage('Foi Gerada ' + IntToStr(LongintVar) + ' Parcela com Sucesso');
     BitBtn_PesquisarCP.Click;
   end
   else
     ShowMessage('Foram Geradas ' + IntToStr(LongintVar) + ' Parcela(s) com Sucesso');
     BitBtn_PesquisarCP.Click;
end;

 

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,7k
×
×
  • Criar Novo...