MariaDB starting with 10.1.1
Starting from MariaDB 10.1.1 compound statements can also be used outside of stored programs
MariaDB [test]> delimiter | MariaDB [test]> if @have_innodb then CREATE TABLE IF NOT EXISTS innodb_index_stats ( database_name VARCHAR(64) NOT NULL, table_name VARCHAR(64) NOT NULL, index_name VARCHAR(64) NOT NULL, last_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, stat_name VARCHAR(64) NOT NULL, stat_value BIGINT UNSIGNED NOT NULL, sample_size BIGINT UNSIGNED, stat_description VARCHAR(1024) NOT NULL, PRIMARY KEY (database_name, table_name, index_name, stat_name) ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin STATS_PERSISTENT=0; end if| Query OK, 0 rows affected, 2 warnings (0.00 sec)
Note, that using compound statements this way is subject to following limitations:
- Only BEGIN, IF, CASE, LOOP, WHILE, REPEAT statements may start a compound statement outside of stored programs.
- BEGIN must use the
BEGIN NOT ATOMICsyntax (otherwise it'll be confused with BEGIN that starts a transaction).
- A compound statement might not start with a label.
- A compound statement is parsed completely — note "2 warnings" in the above example, even if the condition was false (InnoDB was, indeed, disabled), and the
CREATE TABLEstatement was not executed, it was still parsed and the parser produced "Unknown storage engine" warning.
Inside a compound block first three limitations do not apply, one can use anything that can be used inside a stored program — including labels, condition handlers, variables, and so on:
MariaDB [test]> begin not atomic declare foo condition for 1146; declare x int default 0; declare continue handler for foo set x=1; insert into test.t1 values ("hndlr1", val, 2); end|
Example how to use
if (1>0) then BEGIN not atomic select 1; end ; end if;;