因为我的ADOQuery的查询运行时有可能变化,所以它的一个计算字段需要动态添加,我先添加字段,再查询,最后得到的记录集用showmessage(IntToStr(ADOQuery1.Fields.Count))查看为1,郁闷procedure TfrmList.Button1Click(Sender: TObject);
var
  i: word;
  NewField: TFloatField;
begin
  NewField := TFloatField.Create(nil);
  NewField.FieldName := '合计';
  NewField.DataSet := ADOQuery1;
  NewField.FieldKind := fkCalculated;   with ADOQuery1 do
  begin
   SQL.Clear;
   SQL.Add('Select products.品名,list.num as 数量');
   for i := 2 to Grid.Columns.Count-3 do
   begin
     SQL.Add(',(Select Sum(outlist.金额) from outlist,material,products Where outlist.货品=products.编号 And material.material=products.编号');
     SQL.Add('And products.类别='''+Grid.Columns[i].FieldName+''' and material.listid=list.id) as '+Grid.Columns[i].FieldName);
   end;
   SQL.Add(',(Select Sum(outlist.金额) from outlist,products,material Where outlist.货品=products.编号 And material.material=products.编号');
   SQL.Add('And products.库别=1 and material.listid=list.id) as 自制半成品');
   SQL.Add('From products,list,outstore Where products.库别='+IntToStr(Self.Tag));
   SQL.Add('And products.编号=list.product And list.VoucherID=outstore.凭证号 And outstore.日期 between :date1 and :date2');
   Parameters.ParamByName('date1').Value := d1;
   Parameters.ParamByName('date2').Value := d2;
   Open;
  end;

解决方案 »

  1.   

    我发现问题是动态添加字段后,ADOQuery1原来的字段就没有了
    该怎样避免呢?
      

  2.   


    procedure TForm1.Button1Click(Sender: TObject);
    var
      t:TfloatField ;
      d:tstringfield;
    begin
      T := TfloatField.Create(Self);
     T.FieldName := 'CustNo';
      T.Name := 'aa';
      T.Index := table1.FieldCount;
      T.DataSet := table1;
      table1.FieldDefs.UpDate;  d:=tstringfield.Create(self);
      d.Name:='dd';
      d.Index:=table1.FieldCount;
      d.FieldName:='qq';d.DataSet:=table1;
    d.FieldKind:=fklookup;
    d.LookupDataSet:=table2;
    d.KeyFields:='CustNo';
    d.LookupKeyFields:='CustNo';
    d.LookupResultField:='Company';table1.FieldDefs.Update;
    t.Visible:=false;{table1.FieldByName('aa').FieldKind:=fklookup;
    table1.FieldByName('aa').LookupDataSet:=table2;
    table1.FieldByName('aa').KeyFields:='CustNo';
    table1.FieldByName('aa').LookupKeyFields:='CustNo';
    table1.FieldByName('aa').LookupResultField:='Company';  }
    table2.Open;
    table1.Open;end;