以编程方式查找MS-Access 2007表'字段索引'是否存在? TField.IsIndexedField不起作用

时间:2012-02-01 11:24:38

标签: delphi ms-access-2007 ado delphi-2007

我的表客户有一个索引的字段UserID。

enter image description here

现在,当我从delphi中删除此字段时,我将EOleExecption作为其索引字段。 我尝试使用以下代码:

ObjCustomers := TADOTable.Create(nil);    
ObjCustomers.Connection := Connection;        
ObjCustomers.TableName := 'Customers';
ObjCustomers.Open;

if (ObjCustomers.FindField('UserID').IsIndexField) then
begin      
  ExecuteSQLStatements(['DROP INDEX UserID ON Customers']);    
end;

但是对于这种情况,这个Tfield.IsIndexField会出现错误。 此外,我不想做这样的事情:

try      
  ExecuteSQLStatements(['DROP INDEX UserID ON Customers']);    
except 
  on E: exception do    
end;

在执行SQL查询之前,有没有办法检查字段是否为索引?

提前谢谢!

2 个答案:

答案 0 :(得分:4)

GetIsIndexField未实施

TADODataSet,结果将为False

使用TADOConnection.OpenSchema检索表索引:

var DataSet: TADODataSet;

DataSet := TADODataSet.Create(nil);
try
  Connection.OpenSchema(siIndexes, VarArrayOf([Unassigned, Unassigned, Unassigned, Unassigned, 'Customers']), EmptyParam, DataSet);
  while not DataSet.Eof do begin
    ShowMessage(DataSet.FieldByName('INDEX_NAME').AsString);
    DataSet.Next;
  end;
finally
  DataSet.Free;
end;

要完成此答案: 根据{{​​3}}的建议,您可以使用TADODataSet方法TLama ADO内部使用Command.ActiveConnection.OpenSchema(adSchemaIndexes...

function IsIndexField(DataSet: TADODataSet; FieldName: string): Boolean;
var
  SL: TStringList;
begin
  SL := TStringList.Create;
  try
    DataSet.GetIndexNames(SL);
    Result := SL.IndexOf(FieldName) <> -1;
  finally
    SL.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  ObjCustomers: TADOTable;
begin
  ObjCustomers := TADOTable.Create(nil);
  ObjCustomers.Connection := Connection;
  ObjCustomers.TableName := 'Customers';

  if IsIndexField(TADODataSet(ObjCustomers), 'UserID') then
  begin
    Showmessage('Index');
    Connection.Execute('DROP INDEX UserID ON Customers');
  end
  else
    Showmessage('Not Index');

  // ObjCustomers.Open;
  ObjCustomers.Free;
end;

答案 1 :(得分:1)

VAR
 AdoTbl:TAdoDataset;
BEGIN
  AdoTbl:=TAdoDataset.Create(Self); // use TAdoDataset 
  AdoTbl.Connection  :=MyAdoConnection;
  AdoTbl.CommandType:=cmdTable; //Importent !!
  AdoTbl.CommandText:='Refx_Ceramics_Hist_PreHist'; //Tablename 

  AdoTbl.GetIndexNames(ListBox1.Items);
END;

这对我在DelphiXE2上有效