1

I'm having problems while using Tables in a Paradox Data Base in Delphi.

I need to compare two tables and verify which fields are identical and which are different. At the end, both tables must contain the same values on the fields.

However, everything must be done without using SQL, only pure Delphi.

Here is the code so far, but I'm not getting the expected result:

procedure TForm1.Button3Click(Sender: TObject); 
  var  
  s1,s2:string;  
begin  
  Table1.First;  
  while not (Table1.Eof) do  
  Begin 
      s1 := Table1.FieldByName('Campo').AsString; 
      Table2.First; 
      while not (Table2.Eof) do 
      Begin 
          s2 := Table2.FieldByName('Campo').AsString; 

          if (s1 <> s2) then 
          begin 
            Table2.Append; 
            Table2.FieldByName('Campo').AsString := 
                Table1.FieldByName('Campo').AsString; 
          end 
          else if (s1 = s2) then 
          begin 
            Table2.Next; 
          end; 

          Table2.Next; 
      End; 
      Table1.Next;  
  End;
End;
4

2 回答 2

0

您需要进行两次传递才能将丢失的数据从一个表复制到另一个表中。最简单的方法是创建一个过程来为您执行此操作,然后调用它两次:

procedure TForm1.CopyData(const Src, Dest: TTable);
var
  CompareVal: string;
begin
  Src.First;
  while not Src.Eof do
  begin
    CompareVal := Src.FieldByName('Campo').AsString;
    if not Dest.Locate('Campo', CompareVal, []) then
    begin
      Dest.Insert;     // Or Dest.Append;
      Dest.FieldByName('Campo').AsString := CopmareVale;
      Dest.Post;
    end;
    Src.Next;
  end;
end;

像这样称呼它:

procedure TForm1.Button3Click(Sender: TObject);
begin
  CopyData(Table1, Table2);
  CopyData(Table2, Table1);
end;

如果数据库不是很大,这很好用。如果是,您可以通过在要比较的字段上添加索引来提高性能。请参阅 Delphi 帮助TDataSet.Locate,其中包含更多信息和一些指向可能有帮助的其他主题的链接。(链接是当前的 Delphi 帮助,但该信息大部分也适用于 Delphi 7。)

于 2013-04-30T02:42:07.180 回答
-1

阅读所有记录Table2并将Table2.FieldByName('Campo').AsString值放入排序的TStringList. 然后遍历记录Table1并检查stringList.IndexOf所有Table1.FieldByName('Campo').AsString. IndexOf返回 -1 时,将记录追加到Table2. 切换Table1Table2重复。

于 2013-04-30T02:01:13.050 回答