3

I am trying to create a simple procedure which would create a new database. complete code which i am trying to run over mysql is :

SET @DB_NAME := "mydb";
SET @DB_CREATE:= "CREATE DATABASE ";

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 ;

call create_db(@DB_NAME);

I took the help of how do I use a variable in create database statement for creating this procedure. While running this procedure over mysql i am getting error :

ERROR 1046 (3D000): No database selected

I have googled it a lot but is unable to fix it. While trying different things i tried to execute the above procedure by first executing:

mysql> USE mysql;

Using that, error is gone. And

mysql> show databases;

is displaying all the databases along with the newly created database. Could somebody tell me whether using mysql as default database is correct or not. If somebody has another method please tell it to me.

4

2 回答 2

7

使用 ::use database选择要创建 proc 的数据库或

尝试使用databasename.

create procedure databasename.create_db(name TEXT)
于 2013-07-01T10:34:35.480 回答
0

我不相信您可以拥有“全球”的功能,即在数据库范围之外,因此在调用您的功能之前不选择数据库是不可能的

于 2013-07-01T11:01:40.930 回答