Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I use a variable in create database statement

Tags:

mysql

I have this procedure:

DELIMITER //

create DEFINER = 'root'@'localhost' procedure create_db(name TEXT) 
BEGIN
DECLARE temp TEXT;
DECLARE user TEXT;
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = name INTO temp;
  if temp = name then
      SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'This database already exist';
  else
      SELECT USER() INTO user;
      create database name;
      grant all privileges on name.* to user with grant option;
  END IF;
END //

DELIMITER ;

it works great just it supply literally "name" instead of value of variable name. How do I tell it that name is a variable? something like $name in php or that. I browser many documentations but they all are using variable with no prefixes.

like image 734
Petr Avatar asked Mar 06 '13 14:03

Petr


1 Answers

You just need to use prepared statements, here is working code:

DELIMITER //

drop procedure if exists create_db //

create procedure create_db(name TEXT)
BEGIN
  DECLARE temp TEXT;
  DECLARE user TEXT;
  SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = name INTO temp;
  if temp = name then
  SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'This database already exist';
    else
    SELECT USER() INTO user;

    SET @s = CONCAT('CREATE DATABASE ', name);
    PREPARE stmt_create FROM @s;
    EXECUTE stmt_create;
    DEALLOCATE PREPARE stmt_create;

    SET @s = CONCAT('GRANT ALL PRIVILEGES ON ', name, '.* TO ', user, ' WITH GRANT OPTION');
    PREPARE stmt_grant FROM @s;
    EXECUTE stmt_grant;
    DEALLOCATE PREPARE stmt_grant;

  END IF;
END //

DELIMITER ;
like image 142
Rostyslav Avatar answered Sep 30 '22 16:09

Rostyslav