Your
select
GROUP_CONCAT(qry SEPARATOR ' UNION ALL ')
INTO @sql
FROM (
SELECT
CONCAT(' SELECT `acct`,', QUOTE(COLUMN_NAME), ' AS `Business_Unit`,`', COLUMN_NAME, '` AS `value` FROM `', @target_table, '` WHERE ', @target_where) qry
FROM (
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`=@target_schema
AND `TABLE_NAME`=@target_table
AND COLUMN_NAME != 'acct'
) AS `A`
) AS `B` ;
Already assumes that your table
already exists, since it loads information from information_schema.columns
querying for your table, so, your table
must exist before your EXECUTE s
line. But, in my humble opinion, it would be great if you would run your create
command above all the lines above, to make sure that the code is as understandable as possible.
EDIT
The problem discussed in the comment-section was this query:
SELECT CONCAT('CREATE TABLE ', QUOTE(final_results), ' AS ', GROUP_CONCAT(qry SEPARATOR ' UNION ALL ')) INTO @sql
FROM (
SELECT CONCAT('SELECT acct,', QUOTE(COLUMN_NAME), ' AS Business_Unit,', COLUMN_NAME, ' AS value FROM ', @target_table, ' WHERE ', @target_where) qry
FROM ( SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=@target_schema AND TABLE_NAME=@target_table AND COLUMN_NAME != 'acct' ) AS A
) AS B
You need to specify @target_table
just after CREATE TABLE
instead of a column name.
EDIT
The problem is in the highlighted part of the code:

Basically the QUOTE(final_results)
in the SELECT
clause specifies that the column (!!!) called final_results
of the selection (specified by the FROM
clause) needs to be evaluated and escaped into your SELECT
clause and the value with this field will be the name of the new table. But such column does not exist in the relation you defined as B
, given the fact that it only has a
CONCAT('SELECT `acct`,', QUOTE(COLUMN_NAME), ' AS `Business_Unit`,`', COLUMN_NAME, '` AS `value` FROM `', @target_table, '` WHERE ', @target_where) qry
in the SELECT
clause, so your inner query will have a result set that has a single column, called qry
. You therefore tried to select final_results
from a result-set which only has a qry
field. Since the result set you are selecting from does not have a final_results
field, you cannot refer to that either. As a result, you will need to decide for yourself what the table name should be and fix your query accordingly.