DELIMITER //

-- Create procedure --
DROP PROCEDURE IF EXISTS createUser
//

CREATE PROCEDURE createUser()
    BEGIN
	DECLARE a CHAR(16);
	DECLARE cur CURSOR FOR SELECT `user` FROM mysql.db WHERE `user` = '$DB_USER' and `db` = '$DB_NAME';
	DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' 
		BEGIN 
		  CREATE USER $DB_USER IDENTIFIED BY '$DB_PASSWORD';
		  GRANT ALL ON $DB_NAME.* TO '$DB_USER'@'%';	
		END;
	
	OPEN cur;
		
	FETCH cur INTO a;

	CLOSE cur;

    END
//

-- end createUser procedure --
call createUser()
//