How do I use GRANT with variables?
I have some problems with GRANT and variables together in MySql.
SET @username := 'user123', @pass := 'pass123';
GRANT USAGE ON *.* TO @username@'%' IDENTIFIED BY @pass;
GRANT INSERT (header1, header2, headern) ON `data` TO @username@'%';
GRANT SELECT (header1, header2) ON `data2` TO @username@'%';
I would like to put the username and password in variables at the beginning of the script and then use them in GRANT
So instead of this:
GRANT USAGE ON *.* TO 'user123'@'%' IDENTIFIED BY 'pass123';
I would like to use something like this:
GRANT USAGE ON *.* TO @username@'%' IDENTIFIED BY pass;
I would really appreciate it if someone could show me the correct statements. Thank you for that!
+3
source to share
1 answer
SET @object = '*.*';
SET @user = '''user1''@''localhost''';
SET @query = CONCAT('GRANT UPDATE ON ', @object, ' TO ', @user);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
DROP PROCEDURE IF EXISTS `test`.`spTest`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `spTest`( varLogin char(16), varPassword char(64) )
BEGIN
DECLARE varPasswordHashed CHAR(41);
SELECT PASSWORD(varPassword) INTO varPasswordHashed;
# Any of the following 3 lines will cause the creation to fail
CREATE USER varLogin@'localhost' IDENTIFIED BY varPassword;
GRANT USAGE ON test.* TO varLogin@'localhost' IDENTIFIED BY varPassword;
GRANT USAGE ON test.* TO varLogin@'localhost' IDENTIFIED BY PASSWORD varPasswordHashed;
## The following 3 lines won't cause any problem at create time
CREATE USER varLogin@'localhost' IDENTIFIED BY 'AnyPassordString';
GRANT USAGE ON test.* TO varLogin@'localhost' IDENTIFIED BY 'AnyPassordString';
GRANT USAGE ON test.* TO varLogin@'localhost' IDENTIFIED BY PASSWORD 'AnyPassordString';
END$$
DELIMITER;
+3
source to share