Copy Like Fields from One Table to Another

How to duplicate data across tables.

Delphi Developer
Copyright Pinnacle Publishing, Inc. All rights reserved.Copy Like Fields from One Table to Another

Steve Zimmelman



In almost every application that I develop, there comes a time when I need to copy fields from one table to another. Carl Hewitt and I wrote a function called XferFields (see Listing 1) to make it easy. XferFields is similar to the Scatter and Gather commands found in FoxProÊwith the exception that there are no Memory Variables involved, and the transfer of information is made on the current records located in the Source and Destination tables.



XferFields will transfer any fields in the Source to any fields of the same Name and DataType in the Destination table, and returns a Boolean value of False only if all fields in the Destination table fail to be updated. Each time a field transfer attempt fails, an Integer variable is incremented. If the increment count is equal to the Destination table's FieldCount, then it is assumed that no fields were transferred and something is wrong. You can then handle the exception anyway you see fit in your code.



A simple usage for XferFields might look like this:



If XferFields(Table1,Table2) Then

   Table2.Post

Else Begin

   Table2.Cancel ;

   ShowMessage('XferFields Failed!');

End;



Listing 1. The XferFields function.



// **********************************************

// Function XferFields

// Version: Delphi 2.0

// Written By: Carl Hewitt & Steve Zimmelman

// Will transfer any fields in the Source to any

// fields of the same Name and type in the

// Destination.

// If the Destination table is in Browse State,

// it will be placed in Edit State and returned

// the same way.

// **********************************************



Function XferFields(Source, Dest :TDataSet) : Boolean ;

Var

   i : Integer;

   nErr: Integer;

   f1 : TField;

   f2 : TField;



Begin

   // nErr is used to count unsuccessful

   // field transfers

   nErr := 0 ;

   // Make sure Destination table is in

   // Edit state.



   If (Dest.State = dsBrowse) Then

      Dest.Edit ;



      For i := 0 to (Dest.FieldCount -1) Do Begin

         f1 := Dest.FindField(

         Dest.Fields[i].FieldName);

         f2 := Source.FindField(

         Dest.Fields[i].FieldName);



      If (f1 <> nil) And (f2 <> nil) Then Begin

         Try

            // transfer field value

            f1.value := f2.value;

         Except

            // Increment error count

            Inc(nErr);

         End;

      End;

   End;



   // If (nErr = Dest.FieldCount) then

   // no fields were transfered and

   // Result will be False.

   Result := (nErr < Dest.FieldCount);

End;

 

Share this article!

Follow us!

Find more helpful articles: