Search code examples
delphitdataset

Get name of table that TField is from


I'm using a TDataSet where the CommandText property is set to an SQL query. I have also made the following function which creates part of an SQL query based on the fields of TDataSet. It is however incomplete. As you can see I still need to get the name of the table that a TField is from. How do I achieve this?

function GetDataSetFieldsMSSQL(Dataset: TDataSet): String;
var
  I, L: Integer;
  TableName: String;
begin
  Result := '';
  L := Dataset.Fields.Count;
  if (L > 0) then
  begin
    TableName := ... // Name of the table for the Dataset.Fields[0] field.
    Result := '[' + TableName + '].[' + Dataset.Fields[0].FieldName + ']';
    I := 1;
    while (I < L) do
    begin
      TableName := ... // Name of the table for the Dataset.Fields[I] field.
      Result := Result + ',[' + TableName + '].[' + Dataset.Fields[I].FieldName + ']';
      Inc(I);
    end;
  end;
end;

Solution

  • Maybe there is no solution at all for a simple TDataSet?

    I believe not. Because an TDataset can source its' data not only from RDBMS' tables. It can be:

    1. an RSS feed
    2. An XML file. Example: TCliendataset is an TDataset descendant that can read XML from its' own format or using an XMLTransformProvider.
    3. It can be an SQL for reading an Excel spreadsheet or a text file if you have an ODBC driver for that and configured the datasource.
    4. Sky (and the imagination of Delphi's programmers around the world) is the limit for what a field can represent in an TDataset.

    You have some alternatives, since you are using an ADODataset:

    • Parsing the commandText of ADOCommand
    • Using the BASETABLENAME property of ADORecordSet (as in kobik's comment)
    • Guessing by convention ( Abelisto's answer )