mysqlmysql-error-1046

Create procedure ERROR 1046 (3D000): No database selected


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.


Solution

  • Use the :: use database to select the database to which you want the proc to be created or

    try using databasename.

    create procedure databasename.create_db(name TEXT)