用于创建用户的MySQL存储过程

时间:2014-11-15 10:19:14

标签: mysql stored-procedures

我正在尝试创建一个存储过程来在mysql server 5.6.21中创建用户但是它会抛出以下错误:

  

错误代码:1445。不允许从存储的函数设置自动提交   或触发。

以下代码:

CREATE PROCEDURE `add_User`(IN p_Name VARCHAR(45), IN p_Passw VARCHAR(200))
BEGIN

    DECLARE flag_exist TINYINT(1) DEFAULT 0;

    SELECT COUNT(*)
    INTO flag_exist 
    FROM
        `mysql`.`USER`
    WHERE
        `mysql`.`USER`.`User` = p_Name;

    IF flag_exist = 0 THEN 
        CREATE USER p_Name;
        GRANT ALL PRIVILEGES ON *.* TO p_Name;
        SET PASSWORD FOR p_Name = PASSWORD (p_Passw);
        FLUSH PRIVILEGES;

        /* NO FOUNT
            INSERT INTO user VALUES
            ('localhost',p_Name,PASSWORD(p_Passw),'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
        */
    END IF;

END

1 个答案:

答案 0 :(得分:5)

也许这会给你一些想法:

DELIMITER $$

DROP PROCEDURE IF EXISTS `add_User`$$

CREATE PROCEDURE `add_User`(IN `p_Name` VARCHAR(45), IN `p_Passw` VARCHAR(200))
BEGIN
    DECLARE `_HOST` CHAR(14) DEFAULT '@\'localhost\'';
    SET `p_Name` := CONCAT('\'', REPLACE(TRIM(`p_Name`), CHAR(39), CONCAT(CHAR(92), CHAR(39))), '\''),
    `p_Passw` := CONCAT('\'', REPLACE(`p_Passw`, CHAR(39), CONCAT(CHAR(92), CHAR(39))), '\'');
    SET @`sql` := CONCAT('CREATE USER ', `p_Name`, `_HOST`, ' IDENTIFIED BY ', `p_Passw`);
    PREPARE `stmt` FROM @`sql`;
    EXECUTE `stmt`;
    SET @`sql` := CONCAT('GRANT ALL PRIVILEGES ON *.* TO ', `p_Name`, `_HOST`);
    PREPARE `stmt` FROM @`sql`;
    EXECUTE `stmt`;
    DEALLOCATE PREPARE `stmt`;
    FLUSH PRIVILEGES;
END$$

DELIMITER ;