Delphi coding hints and tips.

Creating DB tables at run time

It is possible using a TTable to dynamically create tables at run-time using TTable.CreateTable method. This is useful for creating temporary tables which you can delete on app closing or maybe creating table who's structure is not known until run-time.

Below is a simple example. It creates an instants of TTable and assigns DatabaseName, TableName and Tabletype. Then the structure of the table is defined by use of the TTable.FieldDefs property (check Delphi help for more info). In this case adding just two fields 'id' as an Integer and 'description' as string 55 character long. I have also added a primary and secondary index using TTables.IndexDefs property. Finally I call CreateTable which will create the physical table on disk. Although I then immediately Free the TTable instants after CreateTable you could instead add records to the table, attach it to a TDataSource+TDBGrid and show within a form. Note: The example below does not use a TDatabase/BDE Alias but you could if you wished by assigning DatabaseName to TDatabase.DatabaseName instead of C:\temp.

var
  Tbl:TTable;
begin
Tbl:=TTable.Create(nil);
try
  Tbl.DatabaseName:='C:\temp';
  Tbl.TableName:='TEMP';
  Tbl.TableType:=ttParadox;
  with Tbl do
    begin
    {Fields.}
    FieldDefs.Add('id',ftInteger,0,False);
    FieldDefs.Add('description',ftString,255,False);
    {Primary key.}
    IndexDefs.Add('','id',[ixPrimary]);
    {Secondary key.}
    IndexDefs.Add('sort1','description;id',[ixCaseInsensitive]);
    end;
  Tbl.CreateTable;
finally
  Tbl.Free;
end;