hi there, I am trying to create a stored procedure that i can pass the table name to and it will create a table with that name. but for some reason it creates with what i have defined as the variable name . In the case of the example below it creates a table called 'tname'
for example
CREATE PROCEDURE createtable(tname varchar(20))
BEGIN
DROP TABLE IF EXISTS tname;
CREATE TABLE tname SELECT * FROM anothertable WHERE value = 'something';
END //
now i call it passing my desired table name
mysql> call createtable(accounts);
It works fine apart from the fact it ignores my desired table name of 'accounts' and instead creates a table called 'tname'
Is there something basic i'm doing wrong here?
any help would be greatly appreciated
Cheers
---------- Post updated at 06:13 AM ---------- Previous update was at 04:52 AM ----------
oops, i think ive posted this question in the wrong area, is there any chance a mod could move it to the correct area?
Also, I'm not 100% sure, but I think you have to define the tname parameter explicitly, eg:
CREATE PROCEDURE createtable(IN tname varchar(20))
BEGIN
DROP TABLE IF EXISTS tname;
CREATE TABLE tname SELECT * FROM anothertable WHERE value = 'something';
END //
OK, I've read up on Stored Procedures. Seems you can only use DDL statements if you CONCAT them into a variable, and then use that as a prepared statement.
CREATE PROCEDURE createtable(IN tname varchar(20))
BEGIN
SET @s = CONCAT('DROP TABLE IF EXISTS ', tname);
PREPARE stm FROM @s;
EXECUTE stm;
SET @s = CONCAT('CREATE TABLE ', tname, ' SELECT * FROM anothertable WHERE value = '''something''');
PREPARE stm FROM @s;
EXECUTE stm;
END //
thanks Pludi, after reading the link you posted up earlier, i figured out i needed to use quotes , but thank you anyway it all works perfectly, ive added some kudos via the "thanks" button