Mirror

Coping a record from one Table to Another (Views: 100)


Problem/Question/Abstract:

How can I copy the content of a record of a Table to another with the same or similar structure ?

Answer:

When we want to copy a record from a table to another with the same structure we can use the next function: FILLDBF.

For example: I have two tables: TSource and TDest, I want to copy the current record of TSource to TDest. The code is:

TDest.Append;
FillDbf(TSource, TDest);
TDest.Post;

and the function is

procedure FillDbf(xSource, xDestination: TTable);
var
  xList: TStringList;
  i: Integer;
  xF: TField;
begin
  xList := TStringList.Create;
  xSource.GetFieldNames(xList);
  for i := 0 to xList.Count - 1 do
  begin
    xF := xDestination.FindField(xList[i]);
    if xF <> nil then
      xF.AsVariant := xSource.FieldValues[xList[i]];
  end;
  xList.Free;
end;

The function search for the existence on TDest of every field of TSource, and replace them. TSource and TDest doesnt need to have the same structure because only the fields that match on both are replaced.

With this function is very easy to write a class for improve the performance.

<< Back to main page