Author: Tomas Rutkauskas
I need to copy a record in a dBase table to the same table and just change a value
or two. I know that I can copy the hard way read all the fields into a record then
write it back out.
Answer:
Solve 1:
1 var2 SourceQueryFieldName: string;
3 begin4 QueryDestination.Open;
5 QuerySource.Open;
6 QueryDestination.Insert;
7 for FieldLoop := 0 to QuerySource.FieldCount - 1 do8 begin9 SourceQueryFieldName := DataBaseQuerySource.Fields[FieldLoop].FieldName;
10 try11 QueryDestination[SourceQueryFieldName] := QuerySource[SourceQueryFieldName];
12 except13 {Field not Found}14 end;
15 end;
16 QueryDestination.Post;
17 QueryDestination.Close;
18 QuerySource.Close;
19 end;
Solve 2:
I actually prefer code that reads each field and writes it to the new record like
this:
20 procedure CopyRecord(tbl: TTable);
21 var22 I: Integer;
23 tblTmp: TTable;
24 begin25 blTmp := TTable.Create(nil);
26 try27 tblTmp.DatabaseName := tbl.DatabaseName;
28 tblTmp.TableName := tbl.TableName;
29 tblTmp.Open;
30 ttblTmp.GotoCursor(Src);
31 tbl.Insert;
32 try33 for I := 0 to T.FieldCount - 1 do34 tbl.Fields[I].Assign(tblTmp.Fields[I]);
35 except36 tbl.Cancel;
37 raise;
38 end;
39 finally40 tblTmp.Free;
41 end;
42 end;
43 44 //But you can also do it like this:45 46 procedure CopyRecord(const FromTable: TTable);
47 begin48 dbiInsertRecord(FromTable.Handle, dbiNoLock, FromTable.ActiveBuffer);
49 end;