我的表Customers有一个索引的字段UserID. 现在,当我从delphi中删除此字段时,我将EOleExecption作为其索引字段. 我尝试使用以下代码: ObjCustomers := TADOTable.Create(nil); ObjCustomers.Connection := Connect
现在,当我从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查询之前,有什么方法可以检查字段是否为索引?
提前谢谢!
TADODataSet未实现GetIsIndexField,结果将为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;
要完成此答案:
根据TLama的建议,您可以使用TADODataSet方法GetIndexNames
.
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;