mysql retrieve field names as part of recordset

354 Views Asked by At

I have an application where I must avoid any processing of a MySQL recordset returned from a SELECT query, since interacting with the return in any way results in expensive VBA operations (which crashes MS Excel for large data returns). Instead I pass the recordset directly to a cell range. This requires that the recordset be formatted and sorted by the data server.

I would like my select query to return a recordset, the first row of which is the list of fields. I find myself doing something like this

(SELECT 'ticker', 'name', 'revenue', 'eps')
UNION
(SELECT ticker, name, revenue, EPS, FROM table
WHERE ticker IN
('BLK','DOV','ESL','CSCO','FB','AME','AXP','BAC','BEAV','EL','MMM','IBM'))
ORDER BY 
FIELD(ticker, 'ticker','BLK','DOV','ESL','CSCO','FB','AME','AXP','BAC','BEAV','EL','MMM','IBM')

which feels a little bit ridiculous. Is there really no MySQL built-in function to return field names as a record?

1

There are 1 best solutions below

0
On

You can get the columns from a table like so:

SHOW COLUMNS FROM mytable FROM mydb;

SHOW COLUMNS displays the following values for each table column:

Field indicates the column name.

Type indicates the column data type.

Collation indicates the collation for nonbinary string columns, or NULL for other columns. This value is displayed only if you use the FULL keyword.

The Null field contains YES if NULL values can be stored in the column. If not, the column contains NO as of MySQL 5.0.3, and '' before that.

https://dev.mysql.com/doc/refman/5.0/en/show-columns.html

There are ways of formatting this with your application layer