Many people have asked this question on CSDN before, but no one seems to have given a satisfactory answer. It took me a long time to find the answer, and now I share it with you:
PRocedureTForm1.FormCreate(Sender:TObject);
var
NewField:TField;
i:integer;
begin
//There are two fields in the table, SName and Birth. Now we dynamically generate a calculated field Age to display age.
NewField:=TStringField.Create(ADOTable);
//Create a field of type TStringField
ADOTable.Close;
fori:=0toADOTable.Fields.Count-1do
ADOTable.Fields[0].Free;//Release all static fields
fori:=0toADOTable.FieldDefs.Count-1do
ADOTable.FieldDefs.Items[i].CreateField(ADOTable);
//Dynamicly generate static fields based on field information of FieldDefs
NewField.Size:=5;
NewField.FieldName:='Age';
NewField.FieldKind:=fkCalculated;
//Set this field as a calculated field
NewField.DataSet:=ADOTable;
//Add this field to ADOTable
ADOTable.Open;
end;
procedureTForm1.ADOTableCalcFields(DataSet:TDataSet);
var
YY1,YY2,MM,DD:Word;
TmpDate:TDate;
begin
DecodeDate(Date,YY1,MM,DD);
TmpDate:=DataSet.FieldByName('Birth').AsDateTime;
DecodeDate(TmpDate,YY2,MM,DD);
DataSet.FieldByName('Age').AsString:=IntToStr(YY1-YY2)+'year';
//Display age in OnCalField
end;
The above is what I wrote using ADO. At the beginning, I wrote it using BDE, and it still passed.
Author's Blog: http://blog.csdn.net/blazingfire/