MySQL Add/Grant user if it does not exist I am trying to create a update/install script that adds a user and database only if it's a fresh install. The script uses a randomly generated password for the user, so using the GRANT statement as suggested in a StackOverflow thread will not work.


Is there a way to create, set password, and grant privs a user only if it does not exist?
Am I going to have to run a check in the script and then run the statement or can I build it into a SQL file?
What you need is Dynamic SQL

SET @sql_found='SELECT 1 INTO @x';
SET @sql_fresh='GRANT ALL ON *.* TO randomuser@''%'' IDENTIFIED BY ''randompassword''';
SELECT COUNT(1) INTO @found_count FROM mysql.user WHERE user='randomuser' AND host='%';
SET @sql=IF(@found_count=1,@sql_found,@sql_fresh);
PREPARE s FROM @sql;
EXECUTE s;
DEALLOCATE PREPARE s;


If @found_count is 1, then SELECT 1 INTO @x; will execute. (this query does nothing)

Otherwise, GRANT ALL ON *.* TO randomuser@'%' IDENTIFIED BY 'randompassword';

Give it a Try !!!