t e m p o r a l 
 d o o r w a y 

Copying A Table

 

It seems to be a frequent need that programmers have to copy between tables, sometimes across databases.

You can use the TBatchMove.. that is, if you are using a BDE-based database component. There is no equivalent for the ADOExpress components. But the following code works for both...

It implements a field by field copy, with an external translation table for field names so that the destination table can have a different set of field names.

   TStringList *TranslationTable = new TStringList;

   try
   {
      TranslationTable->LoadFromFile(TranslationTableFilePath);

      FromTable->First();

      while (!FromTable->Eof)
      {
         ToTable->Append();

         for
         (
            int FromTableFieldIndex = 0;
            FromTableFieldIndex < FromTable->FieldCount;
            FromTableFieldIndex++
         )
         {
            String FromFieldName =
               FromTable->Fields->Fields[FromTableFieldIndex]->FieldName;

            String ToFieldName;

            if
               (
                  (
                     (ToFieldName = TranslationTable->Values[FromFieldName]).Length() == 0

                  )// No translation

                  &&
                  (
                     ToTable->FindField(FromFieldName) != NULL // But there is a to field
                  )
               ) // Try the From field name
            {
               ToFieldName = FromFieldName;
            };


             ToTable->FieldByName(ToFieldName)->Value =
                FromTable->FieldByName(FromFieldName)->Value;
         };

         ToTable->Post();
         FromTable->Next();
      };
   }
   __finally
   {
      delete TranslationTable;
   }
;

You can easily improve this, I'm sure.

Copyright © 2004 by Mark Cashman (unless otherwise indicated), All Rights Reserved