0

I have a stored procedure that should create a database using the value of the input variable but instead it just creates a database using the variable name itself.

DELIMITER //
CREATE PROCEDURE proc_createdb (dbname VARCHAR(128))
BEGIN
    CREATE DATABASE dbname;
END //

How can I use the value of dbname instead of creating a database called "dbname".

2

1 Answer 1

3
DELIMITER //
CREATE PROCEDURE proc_createdb (dbname VARCHAR(128))
BEGIN
    SET @theSQL=CONCAT('CREATE DATABASE ',dbname);
    PREPARE stmt1 from @theSQL;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;   
END //
DELIMITER ;

call proc_createdb('fred12236');
use fred12236;
drop schema fred12236;

Please see the MySQL Manual page entitled SQL Syntax for Prepared Statements. Note that they invariably use a CONCAT and User Variables (with an @) and they are flakey if used with DECLARE (local variables).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.