procedure GenerateUpdateScriptsForOldDataCadastro;
  
  // Converts a byte array to its hexadecimal string representation
  function BytesToHex(const Bytes: TBytes): string;
  var
    i: Integer;
  begin
    Result := '';
    for i := 0 to Length(Bytes) - 1 do
      Result := Result + IntToHex(Bytes[i], 2);
  end;

  // Formats SQL values based on their field type, ensuring proper escaping
  function FormatSQLValue(const Value: Variant; const FieldType: TFieldType): string;
  begin
    if VarIsNull(Value) then
      Result := 'NULL'
    else
      case FieldType of
        ftString, ftWideString, ftMemo, ftWideMemo, ftFixedChar, ftFixedWideChar:
          // Escape single quotes by doubling them
          Result := QuotedStr(StringReplace(VarToStr(Value), '''', '''''', [rfReplaceAll]));
        ftDate, ftDateTime, ftTime:
          Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', Value));
        ftInteger, ftSmallint, ftWord, ftLargeint, ftAutoInc, ftFloat, ftCurrency, ftBCD, ftFMTBcd:
          Result := VarToStr(Value);
        ftBytes, ftVarBytes, ftBlob, ftGraphic, ftOraBlob, ftOraClob, ftParadoxOle, ftDBaseOle:
          Result := '0x' + BytesToHex(Value);
        else
          // Default handling for other types
          Result := QuotedStr(StringReplace(VarToStr(Value), '''', '''''', [rfReplaceAll]));
      end;
  end;

var
  QueryStore1, QueryStore2: TUniQuery;
  ScriptFile, ReportFile: TextFile;
  ScriptFileName, ReportFileName: string;
  enderecoId, clienteId: Integer;
  dataCadastro1, dataCadastro2: TDateTime;
  isStore1Newer: Boolean;
  FieldList: TStringList;
  i: Integer;
  FieldName: string;
  ValueStore1, ValueStore2: Variant;
  FieldType: TFieldType;
  Connection: TUniConnection;
  Store2Keys: TDictionary<string, TDateTime>;
  CompositeKey: string;
  SourceQuery, TargetQuery: TUniQuery;
  sqlUpdate: string;
begin
  // Define file names
  ScriptFileName := 'update_data_cadastro.sql';
  ReportFileName := 'update_data_cadastro_report.txt';

  // Assign and open the script file for writing
  AssignFile(ScriptFile, ScriptFileName);
  Rewrite(ScriptFile);
  try
    // Assign and open the report file for writing
    AssignFile(ReportFile, ReportFileName);
    Rewrite(ReportFile);
    try
      // Write headers to the report file
      WriteLn(ReportFile, 'Update Scripts for endereco Records with Older data_cadastro');
      WriteLn(ReportFile, 'Generated on: ' + DateTimeToStr(Now));
      WriteLn(ReportFile, '--------------------------------------------------------');
      WriteLn(ReportFile, '');

      // Initialize database connection
      Connection := DM.LocalServer;
      if not Assigned(Connection) or not Connection.Connected then
        raise Exception.Create('Database connection not available');

      // Initialize queries and dictionary
      QueryStore1 := TUniQuery.Create(nil);
      QueryStore2 := TUniQuery.Create(nil);
      Store2Keys := TDictionary<string, TDateTime>.Create;
      try
        QueryStore1.Connection := Connection;
        QueryStore2.Connection := Connection;

        // Define SQL for store1 and store2
        QueryStore1.SQL.Text :=
          'SELECT endereco_id, cliente_id, data_cadastro ' +
          'FROM centauro001.endereco';

        QueryStore2.SQL.Text :=
          'SELECT endereco_id, cliente_id, data_cadastro ' +
          'FROM centauro005.endereco';

        // Open both queries
        QueryStore1.Open;
        QueryStore2.Open;

        // Populate Store2Keys with composite keys from store2
        while not QueryStore2.EOF do
        begin
          enderecoId := QueryStore2.FieldByName('endereco_id').AsInteger;
          clienteId := QueryStore2.FieldByName('cliente_id').AsInteger;
          dataCadastro2 := QueryStore2.FieldByName('data_cadastro').AsDateTime;

          CompositeKey := Format('%d:%d', [enderecoId, clienteId]);
          if not Store2Keys.ContainsKey(CompositeKey) then
            Store2Keys.Add(CompositeKey, dataCadastro2)
          else
            WriteLn(ReportFile, Format(
              'Duplicate key found in centauro001 for endereco_id=%d and cliente_id=%d.',
              [enderecoId, clienteId]));

          QueryStore2.Next;
        end;

        // Reset QueryStore1 to the first record
        QueryStore1.First;

        // Iterate through each record in centauro001.endereco
        while not QueryStore1.EOF do
        begin
          enderecoId := QueryStore1.FieldByName('endereco_id').AsInteger;
          clienteId := QueryStore1.FieldByName('cliente_id').AsInteger;
          dataCadastro1 := QueryStore1.FieldByName('data_cadastro').AsDateTime;

          CompositeKey := Format('%d:%d', [enderecoId, clienteId]);

          if Store2Keys.ContainsKey(CompositeKey) then
          begin
            dataCadastro2 := Store2Keys[CompositeKey];

            if dataCadastro1 <> dataCadastro2 then
            begin
              isStore1Newer := dataCadastro1 > dataCadastro2;

              if isStore1Newer then
              begin
                // Update store2 with data from store1
                SourceQuery := TUniQuery.Create(nil);
                try
                  SourceQuery.Connection := Connection;
                  SourceQuery.SQL.Text := 'SELECT * FROM centauro001.endereco WHERE endereco_id = :id AND cliente_id = :cid';
                  SourceQuery.ParamByName('id').AsInteger := enderecoId;
                  SourceQuery.ParamByName('cid').AsInteger := clienteId;
                  SourceQuery.Open;

                  if SourceQuery.IsEmpty then
                  begin
                    WriteLn(ReportFile, Format(
                      'Warning: Record not found in centauro001 for endereco_id=%d and cliente_id=%d.',
                      [enderecoId, clienteId]));
                  end
                  else
                  begin
                    TargetQuery := TUniQuery.Create(nil);
                    try
                      TargetQuery.Connection := Connection;
                      TargetQuery.SQL.Text := 'SELECT * FROM centauro005.endereco WHERE endereco_id = :id AND cliente_id = :cid';
                      TargetQuery.ParamByName('id').AsInteger := enderecoId;
                      TargetQuery.ParamByName('cid').AsInteger := clienteId;
                      TargetQuery.Open;

                      if TargetQuery.IsEmpty then
                      begin
                        WriteLn(ReportFile, Format(
                          'Warning: Corresponding record not found in centauro005 for endereco_id=%d and cliente_id=%d.',
                          [enderecoId, clienteId]));
                      end
                      else
                      begin
                        FieldList := TStringList.Create;
                        try
                          // Collect all fields except endereco_id and cliente_id
                          for i := 0 to SourceQuery.FieldCount - 1 do
                          begin
                            FieldName := SourceQuery.Fields[i].FieldName;
                            if (FieldName <> 'endereco_id') and (FieldName <> 'cliente_id') then
                              FieldList.Add(FieldName);
                          end;

                          // Start building the UPDATE statement
                          sqlUpdate := 'UPDATE centauro005.endereco SET ';

                          // Manually concatenate SET clauses
                          for i := 0 to FieldList.Count - 1 do
                          begin
                            FieldName := FieldList[i];
                            ValueStore1 := SourceQuery.FieldByName(FieldName).Value;
                            FieldType := SourceQuery.FieldByName(FieldName).DataType;

                            if i > 0 then
                              sqlUpdate := sqlUpdate + ', ';

                            sqlUpdate := sqlUpdate + Format('%s = %s',
                              [FieldName, FormatSQLValue(ValueStore1, FieldType)]);
                          end;

                          // Append the WHERE clause
                          sqlUpdate := sqlUpdate + Format(' WHERE endereco_id = %d AND cliente_id = %d;',
                            [enderecoId, clienteId]);

                          // Write the UPDATE statement to the script file
                          WriteLn(ScriptFile, sqlUpdate);

                          // Write details to the report file
                          WriteLn(ReportFile, Format(
                            'endereco_id=%d, cliente_id=%d: Updated centauro005.endereco (data_cadastro=%s) ' +
                            'with data from centauro001.endereco (data_cadastro=%s)',
                            [enderecoId,
                             clienteId,
                             DateTimeToStr(dataCadastro2),
                             DateTimeToStr(dataCadastro1)]));
                          WriteLn(ReportFile, sqlUpdate);
                          WriteLn(ReportFile, '--------------------------------------------------------');
                        finally
                          FieldList.Free;
                        end;
                      end;
                    finally
                      TargetQuery.Free;
                    end;
                  end;
                finally
                  SourceQuery.Free;
                end;
              end
              else
              begin
                // Update store1 with data from store2
                SourceQuery := TUniQuery.Create(nil);
                try
                  SourceQuery.Connection := Connection;
                  SourceQuery.SQL.Text := 'SELECT * FROM centauro005.endereco WHERE endereco_id = :id AND cliente_id = :cid';
                  SourceQuery.ParamByName('id').AsInteger := enderecoId;
                  SourceQuery.ParamByName('cid').AsInteger := clienteId;
                  SourceQuery.Open;

                  if SourceQuery.IsEmpty then
                  begin
                    WriteLn(ReportFile, Format(
                      'Warning: Record not found in centauro005 for endereco_id=%d and cliente_id=%d.',
                      [enderecoId, clienteId]));
                  end
                  else
                  begin
                    TargetQuery := TUniQuery.Create(nil);
                    try
                      TargetQuery.Connection := Connection;
                      TargetQuery.SQL.Text := 'SELECT * FROM centauro001.endereco WHERE endereco_id = :id AND cliente_id = :cid';
                      TargetQuery.ParamByName('id').AsInteger := enderecoId;
                      TargetQuery.ParamByName('cid').AsInteger := clienteId;
                      TargetQuery.Open;

                      if TargetQuery.IsEmpty then
                      begin
                        WriteLn(ReportFile, Format(
                          'Warning: Corresponding record not found in centauro001 for endereco_id=%d and cliente_id=%d.',
                          [enderecoId, clienteId]));
                      end
                      else
                      begin
                        FieldList := TStringList.Create;
                        try
                          // Collect all fields except endereco_id and cliente_id
                          for i := 0 to SourceQuery.FieldCount - 1 do
                          begin
                            FieldName := SourceQuery.Fields[i].FieldName;
                            if (FieldName <> 'endereco_id') and (FieldName <> 'cliente_id') then
                              FieldList.Add(FieldName);
                          end;

                          // Start building the UPDATE statement
                          sqlUpdate := 'UPDATE centauro001.endereco SET ';

                          // Manually concatenate SET clauses
                          for i := 0 to FieldList.Count - 1 do
                          begin
                            FieldName := FieldList[i];
                            ValueStore2 := SourceQuery.FieldByName(FieldName).Value;
                            FieldType := SourceQuery.FieldByName(FieldName).DataType;

                            if i > 0 then
                              sqlUpdate := sqlUpdate + ', ';

                            sqlUpdate := sqlUpdate + Format('%s = %s',
                              [FieldName, FormatSQLValue(ValueStore2, FieldType)]);
                          end;

                          // Append the WHERE clause
                          sqlUpdate := sqlUpdate + Format(' WHERE endereco_id = %d AND cliente_id = %d;',
                            [enderecoId, clienteId]);

                          // Write the UPDATE statement to the script file
                          WriteLn(ScriptFile, sqlUpdate);

                          // Write details to the report file
                          WriteLn(ReportFile, Format(
                            'endereco_id=%d, cliente_id=%d: Updated centauro001.endereco (data_cadastro=%s) ' +
                            'with data from centauro005.endereco (data_cadastro=%s)',
                            [enderecoId,
                             clienteId,
                             DateTimeToStr(dataCadastro1),
                             DateTimeToStr(dataCadastro2)]));
                          WriteLn(ReportFile, sqlUpdate);
                          WriteLn(ReportFile, '--------------------------------------------------------');
                        finally
                          FieldList.Free;
                        end;
                      end;
                    finally
                      TargetQuery.Free;
                    end;
                  end;
                finally
                  SourceQuery.Free;
                end;
              end;
            end;

          end;

          // Move to next record in QueryStore1
          QueryStore1.Next;
        end;
      finally
        // Free the queries and dictionary
        Store2Keys.Free;
        QueryStore2.Free;
        QueryStore1.Free;
      end;
    finally
      // Close the report file
      CloseFile(ReportFile);
    end;
  finally
    // Close the script file
    CloseFile(ScriptFile);
  end;

  // Inform the user that the process is complete
  ShowMessage('Update scripts and report have been generated successfully.' + sLineBreak +
    'Script File: ' + ScriptFileName + sLineBreak +
    'Report File: ' + ReportFileName);
end;

----------------
The above unit is giving an empty update_data_cadastro.sql, and the update_dat_cadastr_report.txt is giving this:
Update Scripts for endereco Records with Older data_cadastro
Generated on: 10/11/2024 20:38:41
--------------------------------------------------------

Review the code and tell me what is wrong