2013-04-11 126 views
1

我試圖用存儲過程中EXECUTE語句的值填充表。有沒有辦法執行這個或類似的東西。在VALUES子句中執行語句MYSQL

DELIMITER $$ 
DROP PROCEDURE IF EXISTS `mysql`.`ShowUserGrants` $$ 
CREATE PROCEDURE mysql.ShowUserGrants() 
BEGIN 
    DECLARE done BOOLEAN DEFAULT FALSE; 
    DECLARE strGrant CHAR(100); 
    DECLARE cur1 CURSOR 
     FOR SELECT CONCAT("SHOW GRANTS FOR '",user,"'@'",host,"';") 
      FROM mysql.user 
      WHERE host!='localhost'; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true; 

    OPEN cur1; 

    read_loop:LOOP 
    FETCH cur1 INTO strGrant; 
    IF done THEN 
    CLOSE Cur1; 
     LEAVE read_loop; 
    END IF; 
    SET @a = strGrant; 
    PREPARE strStmt FROM @a; 
    INSERT INTO user_grants (grants) VALUES(EXECUTE strStmt); 
/* EXECUTE strStmt; */ 
    DEALLOCATE PREPARE strStmt; 
    END LOOP; 

END $$ 
DELIMITER ; 

EXECUTE語句按我的意思工作,但需要填充表user_grants。 謝謝。

+0

這個過程將在MySQL 5.0.51和61年5月1日運行。我現在知道EXECUTE staement不能用於INSERT。所以問題就變成了:我怎樣才能完成存儲過程試圖做的事情? – 2013-04-15 19:13:37

回答

1
DELIMITER $$ 

DROP PROCEDURE IF EXISTS `mysql`.`ShowUserGrants` $$ 

CREATE PROCEDURE mysql.ShowUserGrants() 
BEGIN 
    DECLARE done BOOLEAN DEFAULT FALSE; 
    DECLARE strGrant CHAR(100); 
    DECLARE cur1 CURSOR 

     FOR SELECT CONCAT("SHOW GRANTS FOR '",user,"'@'",host,"';") 
      FROM mysql.user 
      WHERE host!='localhost'; 

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true; 

    OPEN cur1; 

    read_loop:LOOP 

    FETCH cur1 INTO strGrant; 

    IF done THEN 
     CLOSE Cur1; 
     LEAVE read_loop; 
    END IF; 

    SET @a = 'INSERT INTO user_grants(grants) VALUES(?)'; 
    PREPARE strStmt FROM @a; 
    SET @var = strGrant; 
    EXECUTE strStmt USING @var; 
    DEALLOCATE PREPARE strStmt; 
    END LOOP; 
END $$ 

DELIMITER ; 

或更好,更換SP機身採用

INSERT INTO user_grants(grants) 
    SELECT CONCAT("SHOW GRANTS FOR '",user,"'@'",host,"';") 
    FROM mysql.user 
    WHERE host!='localhost';