TDataset.CopyFields

Description

Often when manipulating datasets with similar structures, you need to copy the records from one dataset to another.  E.g. you may have fetched some records in a query or clientdaset and have located the matching records in another dataset.  You might then want to ensure the record values match without refetching the target dataset.
This looks like it would be easy to implement - i have rewritten it to take care of nested datasets as well as ordinary dataset fields.
Steps to Reproduce:
This is a requested new public method in the base TDataset class.
function TDataSet.CopyFields(Source: TDataSet): Integer;
// copies matching fields in current records- returns number of fields copied
var
  FieldCtr: Integer;
  DestField, SourceField: TField;
begin
  Result := 0;
  for FieldCtr := 0 to Source.FieldCount - 1 do begin
    SourceField := Source.Fields[FieldCtr];
    Field := FindField(SourceField.FieldName);
    if not Assigned(Field) then Continue;
    if Field.ClassType = TDataSetField then begin  // nested datasets
      while TDataSetField(Field).NestedDataSet.RecordCount > 0 do
        TDataSetField(Field).NestedDataSet.Delete;
      TDataSetField(SourceField).NestedDataSet.First;
      while not TDataSetField(SourceField).NestedDataSet.Eof do begin
        TDataSetField(Field).NestedDataSet.Append;
        CopyFields(TDataSetField(Field).NestedDataSet, TDataSetField(SourceField).NestedDataSet);
        TDataSetField(Field).NestedDataSet.Post;
        TDataSetField(SourceField).NestedDataSet.Next;
      end; 
    end else
      Field.Value := SourceField.Value;
    Inc(Result);
  end;
end;


This would typically be used as follows:

SourceDS.First;
while not SourceDS.EOF do begin
  if DestDS.Locate({info required to find matching record}) then begin
    DestDS.Edit;
    DestDS.CopyFields(SourceDS);
    DestDS.Post;
  end;
  SourceDS.Next;
end; 

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值