在一个数据库应用程序中,我们经常要将记录从一个 dataset 拷贝到另一个 dataset。作为一名 Delphi 程序员,你其实只需要一条命令。
回答:
通常,你完成此项任务时使用 TBatchMove 构件。但 TBatchMove 也有不合适的情况:
- 你并不希望拷贝所有的记录,也不想使用过滤器。
- 你希望用到目的 DataSet 的有效事件(如 BeforPost,OnValidate,等)。
- 或者更坏的情况,两 DataSet 的结构并不相同。
使用下面的简单过程,上面的问题都可以被解决,所有字段中的数据将被拷贝到另外一个 Dataset 中的同名字段中。但这里面也存在一些限制:
- 不能拷贝查找和计算字段
- 当存在相同字段名但数据类型不同时,你需要先使用 Assign 判断。
- 当然,目的字段不能是只读的。
procedure CopyRecord(Source, Destination: TDataSet);
var Ind:longint;
SField, DField: TField;
begin
for Ind:=0 to Source.FieldCount - 1 do
begin
SField := Source.Fields[ Ind ];
DField := Destination.FindField( SField.FieldName );
if (DField < > nil) and (DField.FieldKind = fkData) and
not DField.ReadOnly then
if (SField.DataType = ftString) or
(SField.DataType < > DField.DataType) then
DField.AsString := SField.AsString
else
DField.Assign( SField )
end;
end;
旧方法:
DEST.Open;
ORIGIN.Open;
while not ORIGIN.Eof do
begin
if ORIGINTYPE.AsString = 'T' then
with ORIGIN do
begin
DEST.Append;
DEST.FieldByName('TYPE').AsString := ORIGINTYPE.AsString;
DEST.FieldByName('FIRSTNAME').AsString := ORIGINFIRSTNAME.AsString;
DEST.FieldByName('LASTNAME').AsString := ORIGINLASTNAME.AsString;
DEST.FieldByName('CPF').AsString := ORIGINCPF.AsString;
DEST.FieldByName('PARTY').AsString := ORIGINPARTY.AsString;
DEST.Post;
end;
ORIGIN.Next;
end;
使用该过程的调用示范:
DEST.Open;
ORIGIN.Open;
while not ORIGIN.Eof do begin
if ORIGINTYPE.AsString = 'T' then begin
DEST.Append;
CopyRecord( ORIGIN, DEST );
DEST.Post;
end;
ORIGIN.Next;
end;
此过程在使用 TQueries, TClientDataSet 和其它 TDataset 子类时,工作良好。
希望对大家有所帮助。.
|