使用特定名称删除MySQL中的所有用户

时间:2012-08-12 21:07:09

标签: mysql

我想删除具有指定名称的MySQL数据库中的所有用户,而不管host参数如何。这是我写的:

DELIMITER ;;

## CREATING SCHEMA
DROP SCHEMA IF EXISTS rms;;
CREATE SCHEMA rms;;

USE rms;;

## DROP USER
DROP PROCEDURE IF EXISTS PREPARE_USERS;;
CREATE PROCEDURE PREPARE_USERS()
BEGIN
    DECLARE V_RECORD_NOT_FOUND INTEGER DEFAULT 0; 
    DECLARE V_USER_HOST CHAR(60);
    DECLARE C_HOSTS_CURSOR CURSOR FOR
        SELECT host FROM mysql.user WHERE user='rms';
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET V_RECORD_NOT_FOUND = 0;

    OPEN C_HOSTS_CURSOR;

    READ_LOOP: LOOP
        FETCH C_HOSTS_CURSOR INTO V_USER_HOST;
        IF V_RECORD_NOT_FOUND != 0 THEN
            LEAVE READ_LOOP;
        END IF;

        SET @V_EXEC=CONCAT(CONCAT('DROP USER \'rms\'@\'',V_USER_HOST),'\';;');
        PREPARE V_STMT FROM @V_EXEC;
        EXECUTE V_STMT;
        DEALLOCATE PREPARE V_STMT;
    END LOOP;

    CLOSE C_HOSTS_CURSOR;

    FLUSH PRIVILEGES;

    CREATE USER 'rms'@'127.0.0.1' IDENTIFIED BY 'rms123';
    GRANT ALL ON rms.* TO 'rms'@'127.0.0.1'
    WITH MAX_USER_CONNECTIONS  250;
END;;

CALL PREPARE_USERS();;

DROP PROCEDURE IF EXISTS PREPARE_USERS;;

DELIMITER ;

但它给了我错误,我不知道为什么:/当没有'rms'名称的用户时,它甚至不会运行,但如果有,MySQL声称它们不能被删除即使它们是。

1 个答案:

答案 0 :(得分:4)

好的,我有答案:

SET @users = NULL;
SELECT GROUP_CONCAT('\'',user, '\'@\'', host, '\'') INTO @users FROM mysql.user WHERE user = 'rms';

SET @users = CONCAT('DROP USER ', @users);
PREPARE stmt1 FROM @users;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;