Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting to selected table name

Tags:

sql

mysql

I have got a table called Aliases in my MySQL database.

Looks like this:

------------------
| Id    | Alias  |
------------------
|1      | 'TabX' |
------------------
|2      | 'TabY' |

...    

|       |        |
------------------

And I need to insert to those tables like this:

INSERT INTO (SELECT Alias FROM Aliases WHERE id=1) (somevalue) VALUES (value);

This doesn't work. Please help.

like image 345
Ivan Fridrich Avatar asked Apr 08 '26 20:04

Ivan Fridrich


1 Answers

You can reach it with prepared statements:

SET @alias = (SELECT Alias FROM Aliases WHERE id = 1);
SET @sql = CONCAT('INSERT INTO ', @alias, ' (somevalue) VALUES (value)');
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;
like image 156
cn007b Avatar answered Apr 10 '26 10:04

cn007b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!