delphisortingindexingdbf

Sorting a table physically in Delphi


Delphi does not seem to like multi-field indexes.

How do I physically sort a a table so that I wind up with a table that has the rows in the desired order?

Example:

mytable.dbf

Field   Field-Name   Field-Type   Size
  0     Payer        Character     35
  1     Payee        Character     35
  2     PayDate      Date
  3     Amount       Currency

I need to produce a table sorted alphabetically by "Payee"+"Payer"

When I tried using an index of "Payee+Payer", I got an error:

"Field Index out of range"


Solution

  • If you're still using BDE you can use the BDE API to physically sort the DBF table:

    uses
      DbiProcs, DbiTypes, DBIErrs;
    
    procedure SortTable(Table: TTable; const FieldNums: array of Word; CaseInsensitive: Boolean = False; Descending: Boolean = False);
    var
      DBHandle: hDBIDb;
      RecordCount: Integer;
      Order: SORTOrder;
    begin
      if Length(FieldNums) = 0 then
        Exit;
    
      Table.Open;
      RecordCount := Table.RecordCount;
      if RecordCount = 0 then
        Exit;
      DBHandle := Table.DBHandle;
      Table.Close;
    
      if Descending then
        Order := sortDESCEND
      else
        Order := sortASCEND;
    
      Check(DbiSortTable(DBHandle, PAnsiChar(Table.TableName), nil, nil, nil, nil, nil,
        Length(FieldNums), @FieldNums[0], @CaseInsensitive, @Order, nil, False, nil, RecordCount));
    end;
    

    for example, in your case:

      SortTable(Table1, [2, 1]); // sort by Payee, Payer