我的表客户有一个索引的字段UserID。
现在,当我从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查询之前,有没有办法检查字段是否为索引?
提前谢谢!
答案 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上有效