Search code examples
mysqlsql-grant

How to use GRANT with variables?


I have some troubles 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'd like to put username and password into variables at the begining of the script and then later use them in GRANT

So instead of this:

GRANT USAGE ON *.* TO 'user123'@'%' IDENTIFIED BY 'pass123';

I'd like to use something like this:

GRANT USAGE ON *.* TO @username@'%' IDENTIFIED BY pass;

I'd really appreciate, if someone could show me the proper statements. Thank you in advence!


Solution

  • 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;