Mega Code Archive

 
Categories / Delphi / ADO Database
 

How to quickly copy a record from one DataSet to another

Title: How to quickly copy a record from one DataSet to another Question: Frequently, in a database application, you must copy records from one dataset to another. You could always acomplish this task with a COBOL approach, copying every field painfully. But you are a Delphi programmer, and you can do it gracefully with just one command. Answer: Usually, you can acomplish this task using TBatchMove component. But there are some situations where TBatchMove doesn't fit: - imagine that you don't want to copy all records, and don't want to use filters. - you want to use the destination dataset validation events (BeforePost, OnValidate, etc) - or even worse, the datasets structures are different. The solution can be done in a simple procedure: you just have to copy all fields with the same name from one dataset to another. But there are some pitfalls: - you can't copy Lookup and CalcFields - you should use Assign when fields have the same name but have different datatype. - your destination field can't be readonly. 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; Here an example using a COBOL or VB Approach: 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; The same solution using a Delphi elegant procedure: 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; This procedure works fine with TQueries, TClientDataSet and any other TDataset-descendents. I hope this tip can be useful to other database programmers. Health and Freedom, Josir.