简体   繁体   中英

mysql create temp table column using select command

i need to create a temporary table which column name will generate dynamically using a select command (mean: the value of another table.). But when i run the command then the temp table created with the value not the column name. i have tried as below:

SELECT ColVal FROM tableA

TableA

------------------------
ColName | ColVal 
------------------------
id      | 1
----------------------
Name    | Test
----------------------
Age     |25
---------------------

Now , i need to create Temp table B which column name will be as below

TableB

--------------
id| Name| Age|
--------------

I have tried by the query:

CREATE TEMPORARY TABLE  TableB as (select ColName  from TableA) 

it's not give me the actual output. it create the table like:

TableB

-----------------
ColName
-----------------
id
--------
Name
--------
Age
--------

I'm not sure that it is the best way to do it, but you can run dynamically constructed sql. You can do something like that:

SELECT  CONCAT("CREATE TEMPORARY TABLE TableB (", 
               group_concat( CONCAT(ColName, " VARCHAR(50)")), ");")
               INTO @Expression
FROM TableA;

PREPARE myquery FROM @Expression;
EXECUTE myquery;

@Expression will be equal to: CREATE TEMPORARY TABLE TableB (id VARCHAR(50),Name VARCHAR(50),Age VARCHAR(50));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM