Every now and then there is a need to execute certain SQL
statements conditionally. Easy, if you do it from your PHP (or
Java or whatever) application. But if all you have is pure SQL?
There are two techniques that MariaDB and MySQL use in the
mysql_fix_privilege_tables.sql script (applied by
- Create a stored procedure with
IFstatements inside, call it once and drop it. This requires the user to have the
CREATE ROUTINEprivilege and
mysql.proctable must exist and be usable (which is not necessarily true — we’re doing it from mysql_upgrade, right?).
- Use dynamic SQL, like
SET @str = IF (@have_csv = 'YES', 'CREATE TABLE IF NOT EXISTS general_log ( event_time TIMESTAMP(6) NOT NULL, user_host MEDIUMTEXT NOT NULL, thread_id BIGINT(21) UNSIGNED NOT NULL, …