2012-08-12 94 views
0

我想要以指定名稱從我的MySQL數據庫中刪除所有用戶,而不管主機參數如何。下面是我寫的:以特定名稱刪除MySQL中的所有用戶

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

你爲什麼讓這個如此複雜 - 什麼是錯用一個簡單的DELETE FROM表其中username LIKE '%FOO%'; – 2012-08-12 21:10:29

+0

據我所知,你不應該直接從mysql.user中刪除,我是否正確? – BartoszCichecki 2012-08-12 21:11:34

+0

你從哪裏看到的?是的,你需要刷新權限後,但據我所知沒有說明這一點。 – 2012-08-12 21:38:46

回答

3

OK,我找到了答案:

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; 
相關問題