Question

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;
Was it helpful?

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 )

OTHER TIPS

You can use the Delphi Function GetTableNameFromQuery(SQL : String):String; from the DBCommon unit. Just Add The DBCommon on the uses. =)

As I know there is no any way to get the name of the table from the SQL query component. However you can give aliases for fields, for example: "select foo_field as foo_dot_foo_field from foo" and then replace them to the correct syntax: "Result := '[' + StringReplace(DataSet.Fields[0].FieldName, 'dot', '].[', [rfReplaceAll]) + ']'"

What you are trying to do is impossible if you have no knowledge or control over the SQL used in the query. The query could contain calculated/computed fields or could be returning fields from a view etc. Furthermore the database might have several tables that contain the same field names.

If possible you can query the SQL server view INFORMATION_SCHEMA.COLUMNS and that way try to figure out what table a fieldname is from. However if the field names are not unique this might also prove impossible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top