5

Stored procedure code:

CREATE DEFINER = `root` @`localhost` PROCEDURE `P_CreateUser3` (
  IN _Username NVARCHAR(30), IN _Password NVARCHAR(32), IN _DBName VARCHAR(20))
BEGIN
  CREATE USER _Username @'localhost' IDENTIFIED BY _Password ;
  GRANT SELECT, UPDATE, DELETE, INSERT 
  ON    _DBName.* 
  TO    _Username @'localhost' 
  WITH GRANT OPTION ;
END $$

Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '_Password ; GRANT SELECT, UPDATE, DELETE, INSERT ON `pr' at line 6

help me please.

4
  • 2
    The unsupported use of stored procedure input parameters as passwords in a CREATE USER or GRANT statement is documented in this bug. Commented Jul 6, 2012 at 20:19
  • 1
    Hmm I wouldn't have even tried that. Just reached straight for exec('SomeQuery') Commented Jul 6, 2012 at 20:28
  • @eggyal Looks like I had it as an answer originally. I restored and undeleted it. Commented Sep 4, 2012 at 16:20
  • possible duplicate of MySQL CREATE USER with a variable? Commented Apr 22, 2014 at 5:21

2 Answers 2

4

Unfortunately, the use of stored procedure input parameters as passwords in a CREATE USER or GRANT statement is documented in this bug as unsupported. So you cannot actually do what you attempted.

It would be possible to PREPARE and EXECUTE a statement which is built by CONCAT() to concatenate in the new password, but this is not a secure method and is therefore not recommended. You lose all the security benefits of the stored procedure if you were to do it that way.

Sign up to request clarification or add additional context in comments.

Comments

0

You must use prepared statements because the variables doesn't evaluate directly in queries.

DELIMITER $$

DROP PROCEDURE IF EXISTS `create_user`$$

CREATE PROCEDURE `create_user`(
    `user_name` VARCHAR(50), 
    `passwd` VARCHAR(255),
    `ip` VARCHAR(50)
)
BEGIN
   set @sql = concat("CREATE USER '",`user_name`,"'@'",`ip`,"' IDENTIFIED BY '",`passwd`,"'");
   PREPARE stmt1 FROM @sql;
   EXECUTE stmt1;
   DEALLOCATE PREPARE stmt1;

   set @sql = concat("GRANT ALL PRIVILEGES ON * . * TO '",`user_name`,"'@'",`ip`,"' ");
   PREPARE stmt2 FROM @sql;
   EXECUTE stmt2;
   DEALLOCATE PREPARE stmt2;

   FLUSH PRIVILEGES;
END$$

DELIMITER ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.