[英]How to delete all records matching a certain value in a FireDAC dataset?
我有一個通常的while not EOF do
循環, while not EOF do
循環從內存表中刪除某些記錄。 刪除最后一條記錄並不表示EOF符合預期。 這是我的代碼:
mtCt.First;
while Not mtCt.Eof do
begin
if mtCtAmt.Value = 0.0 then
mtCt.Delete
else
mtCt.Next;
end;
如何刪除FireDAC數據集中與某個值匹配的所有記錄?
您必須轉到最后一個數據。
mtCt.Last;
while Not mtCt.Bof do
begin
if mtCtAmt.Value = 0.0 then
mtCt.Delete
else
mtCt.Prior;
end;
這是所有Delphi數據集的正常行為。
如果您的刪除邏輯像您的示例一樣簡單,則可以簡單地忽略它,無論如何,下一次迭代將不滿足刪除條件,發出Next並進行EOF。
相反,如果邏輯很復雜並且您需要避免不必要的迭代,則可以使用以下技巧:
var
PrevRecNo: Integer;
begin
mtCt.First;
while Not mtCt.Eof do
begin
if mtCtAmt.Value = 0.0 then
begin
// save the current record number
PrevRecNo := mtCt.RecNo;
// delete will normally not change current record number
// unless you've deleted the last record, in this case
// the current record will be one less than before
mtCt.Delete;
// so, if the saved record number and the current one are
// different, you've delete the last record, just issue a
// Next in order to hit EOF and exit the while loop
if mtCt.RecNo <> PrevRecNo then
mtCt.Next;
end
else
mtCt.Next;
end;
您可以在不導航數據集的情況下訪問內部存儲,例如:
function GetFieldIndex(Dataset: TFDDataSet; const FieldName: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Dataset.Table.Columns.Count-1 do
if Dataset.Table.Columns[I].Name = FieldName then
begin
Result := I;
Break;
end;
end;
procedure DeleteFromDataset(Dataset: TFDDataSet; const FieldName: string;
const FieldValue: Variant);
var
Col, Row: Integer;
begin
Col := GetFieldIndex(Dataset, FieldName);
if Col <> -1 then
begin
Dataset.BeginBatch;
try
{ delete all rows without navigating through dataset; this should
affect also rows that were about to be inserted but changes were
not yet applied }
for Row := Dataset.Table.Rows.Count-1 downto 0 do
if Dataset.Table.Rows[Row].GetData(Col) = FieldValue then
Dataset.Table.Rows[Row].Delete;
{ resync dataset with the just modified internal storage }
Dataset.Resync([]);
finally
Dataset.EndBatch;
end;
end;
end;
用法:
DeleteFromDataset(FDMemTable, 'MyField', 0.0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.