1

我正在尝试使用存储过程中 EXECUTE 语句中的值填充表。有没有办法执行这个或类似的东西。

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。谢谢。

4

1 回答 1

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 body 替换为

INSERT INTO user_grants(grants)
    SELECT CONCAT("SHOW GRANTS FOR '",user,"'@'",host,"';")
    FROM mysql.user 
    WHERE host!='localhost';
于 2013-05-11T16:57:08.313 回答