Search code examples
delphidelphi-xe2dbexpress

DBExpress: How to find a primary key field?


I have a TSimpleDataSet based on dinamically created SQL query. I need to know which field is a primary key?

SimpleDataSet1.DataSet.SetSchemaInfo(stIndexes, 'myTable' ,'');

This code tells me that i have a primary key with name 'someName', but how can i know which field (column) works with this index?


Solution

  • A Primary Key/Index can belong to several columns (not just one).

    The schema stIndexes dataset will return the PK name INDEX_NAME and the columns that construct that PK/Index (COLUMN_NAME). INDEX_TYPE will tell you which index types you have (eSQLNonUnique/eSQLUnique/eSQLPrimaryKey).

    I have never worked with TSimpleDataSet but check if the indexes information is stored in IndexDefs[TIndexDef].Name/Fields/Options - if ixPrimary in Options then this is your PK. and Fields belongs to that index.

    Take a look at the source at SqlExpr.pas: TCustomSQLDataSet.AddIndexDefs. Note how TCustomSQLDataSet returns the TableName (and then the indexs information) from the command text:

      ...
      if FCommandType = ctTable then
        TableName := FCommandText
      else
        TableName := GetTableNameFromSQL(CommandText);
      DataSet := FSQLConnection.OpenSchemaTable(stIndexes, TableName, '', '', '');
      ...