Mysql insert into table (table name is inside a variable) gives Error Code: 1064

The following procedure creates a new table and ‘should populate it with data from a select statement using INSERT INTO. If I test queries separately they work fine but in a form of bellow code it gives error.

CREATE DEFINER=`root`@`localhost` PROCEDURE `testing_temp_table_insert`   (    IN temp_table TEXT ) BEGIN  SET @temp_table = temp_table; SET @c = CONCAT('CREATE TABLE `',@temp_table, '` LIKE already_existing_table`'); PREPARE stmt from @c; EXECUTE stmt; DEALLOCATE PREPARE stmt;  SET @c = CONCAT('INSERT INTO `', @temp_table, '`                   (something, something_else)                  (SELECT (CASE WHEN length(ltrim(rtrim(some_table.something))) > 0                                 THEN some_table.something                                 ELSE '' END) as something,                          some_table.something_else                   FROM some_table;');  PREPARE stmt from @c; EXECUTE stmt;  END 

OK… if I separately test these queries:

This one successfully creates a temporary table under parameters ‘temp_table’ name:

SET @temp_table = temp_table; SET @c = CONCAT('CREATE TABLE `',@temp_table, '` LIKE already_existing_table`'); PREPARE stmt from @c; EXECUTE stmt; DEALLOCATE PREPARE stmt; 

But this one is giving me the error:

In its purest form like….

INSERT INTO already_existing_table  (something, something_else) (SELECT (CASE WHEN length(ltrim(rtrim(some_table.something))) > 0                THEN some_table.something                ELSE '' END) as something,         some_table.something_else  FROM some_table;'); 

works perfectly… but when written like this … (@temp_table is the same as already_existing_table)

 SET @c = CONCAT('INSERT INTO `', @temp_table, '`                   (something, something_else)                  (SELECT (CASE WHEN length(ltrim(rtrim(some_table.something))) > 0                                 THEN some_table.something                                 ELSE '' END) as something,                          some_table.something_else                   FROM some_table;');  PREPARE stmt from @c; EXECUTE stmt; 

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ” END) as something

I get this is probably because of empty string ‘ ‘ which confuses the execution of the whole code but I can’t find the way around it as I’d like to leave the empty string option instead of null field.

Hopefully the question makes sense and attracts your attention. Thanks