Insert into selected table name
I have a table under aliases in my MySQL database.
Looks like:
------------------
| Id | Alias |
------------------
|1 | 'TabX' |
------------------
|2 | 'TabY' |
...
| | |
------------------
And I need to insert into those tables like this:
INSERT INTO (SELECT Alias FROM Aliases WHERE id=1) (somevalue) VALUES (value);
This does not work. Please, help.
+3
source to share
3 answers
For this you need to do PROCEDURE
. And use prepared statements for this purpose. You need a procedure like this:
DELIMITER $$
DROP PROCEDURE IF EXISTS `DB`.`INSERT_VAR`$$
CREATE DEFINER=`user`@`host` PROCEDURE INSERT_VAR(IN tableName VARCHAR(200))
BEGIN
SET @insert_query=CONCAT("INSERT INTO ", tableName, " (id) SELECT id FROM test");
PREPARE stmtInsert FROM @insertTab;
EXECUTE stmtInsert;
END$$
DELIMITER ;
You need to modify this procedure according to your needs.
0
source to share