开发者

How to control the order of Fields in TQuery

开发者 https://www.devze.com 2023-03-11 03:18 出处:网络
I am using Delphi 7. TQuery connected to Firebird DB. Table T1 has 3 fields (A, B, and C). To query that table, I wrote the following code:

I am using Delphi 7. TQuery connected to Firebird DB.

Table T1 has 3 fields (A, B, and C).

To query that table, I wrote the following code:

MyQuery.SQL.Clear;
MyQuery.SQL.Add('SELECT B, C, A FROM T1'); // because that's the order I want them
MyQuery.Open;

However, when filling a string grid's top row with FieldNames (by iterating through the Fields[] array) I don't want to have to rely on static fieldname to column mapping, but my problem is that the order of fields in the Fields[] array doesn't match the order of the fields in the SQL I used.

EDIT

I'm using one routine for multiple reports with different SQLs at runtime. I don't want to rely on FieldNames at all, so I need to make the TQuery.Fields array sorted in the order of the fields appearing in the SQL in TQuery.SQL (at runtime).

My question is: how can I control the order of the Fields in MyQuery.Fields[] so that it matches the order I used i开发者_C百科n the SQL? Is there a better alternative that I should try?

EDIT

Sorry, it was just a silly bug in the end. One too many SQL.Clear!


First of all, this:

MyQuery.SQL.Add('SELECT B, C, A FROM T1');

should be:

MyQuery.SQL.Text := 'SELECT B, C, A FROM T1';

or:

MyQuery.SQL.Clear;
MyQuery.SQL.Add('SELECT B, C, A FROM T1');

because Add() alone appends something to the existing query in MyQuery.SQL. In that case the behavior would be provider-dependent. With some providers you simply get the first query executed and the other ones ignored, while with other providers you'd get an error. Either way it's wrong.

If that still doesn't fix it, what Query are you talking about, what kind of database and what kind of grid? The behavior might be database-dependent or grid-dependent; For what it's worth, I've never seen it happen before, I always got the columns in SQL order. But I'm mostly using Firebird, MsSQL, a little Oracle.


DataSet's Fields collection items can be rearranged in Fields Editor that you can access from mouse right-click menu on the TQuery component.

0

精彩评论

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