Delete all users in MySQL with specific name

五迷三道 提交于 2021-02-20 05:08:38

问题


I want to delete all users from my MySQL database with specified name regardless to the host parameter. Here is what I wrote:

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 ;

But it gives me errors and I don't know why :/ When there are no users with 'rms' name, it won't even run, but if there are any, MySQL claims that they can't be dropped even though they are.


回答1:


OK, I have the answer:

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;


来源:https://stackoverflow.com/questions/11925890/delete-all-users-in-mysql-with-specific-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!