5

我有这个程序:

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 ;

它工作得很好,只是它提供字面上的“名称”而不是变量名称的值。我如何告诉它名称是一个变量?php 中的 $name 之类的东西。我浏览了许多文档,但它们都使用没有前缀的变量。

4

1 回答 1

6

您只需要使用准备好的语句,这是工作代码:

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 ;
于 2013-03-06T14:28:23.640 回答