Mega Code Archive

 
Categories / Delphi / ADO Database
 

Copy a table (struct & content)

Title: Copy a table (struct & content) Question: How can i copy a table ? Answer: There is an easy way to copy a whole database table with the TTable component: procedure CopyTableStructure(Source: TTable; DB,Dest: string); var NewTable: TTable; begin NewTable := TTable.Create(self); with NewTable do begin Databasename := DB; Tablename := Dest; FieldDefs.Assign(Source.FieldDefs); IndexDefs.Assign(Source.IndexDefs); CreateTable; NewTable.Destroy; end; end; The parameters that you have to pass to this function is an open TTable object, the BDE alias and the name of the new table: Table1.Active := true; CopyTableStructure(Table1,'DBALIAS','NewTable'); Copying the whole content is also easy: var hs: string; i: integer; ... Source.First; with NewTable do begin while not Source.EOF do begin Append; for i := 0 to Source.FieldCount - 1 do begin hs := Source.Fields[i].FieldName; NewTable[hs] := Source[hs]; end; Source.Next; end; end; 'Source' has to be from type TDataset (e.g: TTable, TQuery or TClientDataset) !