开发者

"Field 'COUNT(id)' has no dataset" TSQLQuery in Delphi

Sorry for my english, but i hope you'll understand me :P

I'm trying to create new TSQLQuery component in code, without placing it on form. I wrote that code:

var
sql:tsqlquery;
pole:TFMTBCDField;

....
   sql:=开发者_如何学运维tsqlquery.Create(self);
   sql.SQLConnection:=ddm.konekszyn;
   sql.SQL.Text:='SELECT COUNT(idrap) FROM raporty WHERE idkier="'+lvkierowcy.Selected.Caption+'";';
   pole:=TFMTBCDField.Create(self);
   pole.Name:='sqlilerap';
   pole.FieldName:='COUNT(idrap)';
   pole.FieldKind:=fkData;
   pole.DisplayLabel:='COUNT(idrap)';

   sql.Fields.Add(pole);
   sql.Open;
   showmessage(sql.FieldByName('COUNT(idrap)').AsString);
   sql.Free;
   pole.Free;

but i'm getting exception when i try to access data:

First chance exception at $75999617. Exception class EDatabaseError with message 'Field 'COUNT(idrap)' has no dataset'. Process htstrm2.exe (2308)

What should I do ?


Don't even make a field. Queries such as this return one and only one field. So just reference from the fields array:

var
sql:tsqlquery;

....
   sql:=tsqlquery.Create(self);
   sql.SQLConnection:=ddm.konekszyn;
   sql.SQL.Text:='SELECT COUNT(idrap) FROM raporty WHERE idkier="'+lvkierowcy.Selected.Caption+'";';
   sql.Open;
   showmessage(sql.fields[0].AsString);
   sql.Free;


Your database driver reports the empty field name for the aggregate expression.

Alias your field:

   sql:=tsqlquery.Create(self);
   sql.SQLConnection:=ddm.konekszyn;
   sql.SQL.Text:='SELECT COUNT(idrap) AS cnt FROM raporty WHERE idkier="'+lvkierowcy.Selected.Caption+'";';
   pole:=TFMTBCDField.Create(self);
   pole.Name:='sqlilerap';
   pole.FieldName:='cnt';
   pole.FieldKind:=fkData;
   pole.DisplayLabel:='cnt';

   sql.Fields.Add(pole);
   sql.Open;
   showmessage(sql.FieldByName('cnt').AsString);
   sql.Free;
   pole.Free;


You must explicitly assign the dataset to the field, try adding this line

pole.DataSet:=sql;

Bye.


Alias the column being returned. You can then access it by that aliased name:

sql.SQL.Text:='SELECT COUNT(idrap) AS iDrapCount FROM raporty WHERE dkier 
="'+lvkierowcy.Selected.Caption+'";';
....
pole.FieldName := 'iDrapCount';


Try adding this line to your query:

AND idrap <> nil
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜