1

I want to test if a user exists. If it does I should do nothing. If it doesn't I should create it and grant privileges.

The concept code that I came up with is this:

IF EXISTS(SELECT 1 FROM mysql.user WHERE user = 'web_service_user' AND host = '%') THEN 
   \! echo "EXISTS";
ELSE 
   \! echo "DOES NOT";
END IF;

Hower when I run this I get this output:

EXISTS
DOES NOT
ERROR 1064 (42000) at line 1 in file: 'test_conditional.sql': You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ELSE 
   
END IF' at line 3

So how do I test (in a conditional) if a user exists?

I know of this: mysql create user if not exists

However I would need still need to check if the user "was just created" in order to know If I need to execute the grant statements.

aarelovich
  • 5,140
  • 11
  • 55
  • 106
  • IF statement can be used in named compound statement (stored procedure, for example) only. – Akina Nov 08 '20 at 10:17
  • Ahh Ok. I didn't know that. Kind of a newbie here. – aarelovich Nov 08 '20 at 10:18
  • *how do I test (in a conditional) if a user exists?* `SELECT CASE WHEN EXISTS(SELECT 1 FROM mysql.user WHERE user = 'web_service_user' AND host = '%') THEN 'Exists' ELSE 'Does not' END AS Existence_Check;` – Akina Nov 08 '20 at 10:19
  • @aarelovich This might help [usage-of-if-exist-in-mysql](https://stackoverflow.com/questions/5528854/usage-of-mysqls-if-exists) – abhijit gupta Nov 08 '20 at 10:25

0 Answers0