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 in 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:
should be:
or:
because
Add()alone appends something to the existing query inMyQuery.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
Queryare 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.