Home > Software design >  Correct usage of If/else condition in MySQL based on a session variable
Correct usage of If/else condition in MySQL based on a session variable

Time:11-12

If I set a session variable (eg. @tmp = 0), then a query can be run/ignored depending on whether a condition is met.

SET @create_table := IF(@tmp >= 1, 'CREATE TABLE table2 SELECT * FROM table1', 'no');

This is usable for a short query like the example above, but not so for more complex queries with multiple statements. Is it possible to do something like this?

IF(@tmp >= 1)
DO SOMETHING
ELSE
DO NOTHING

CodePudding user response:

The correct syntax is as follow.

IF condition1 THEN
   {...statements to execute when condition1 is TRUE...}

[ ELSEIF condition2 THEN
   {...statements to execute when condition1 is FALSE and condition2 is TRUE...} ]

[ ELSE
   {...statements to execute when both condition1 and condition2 are FALSE...} ]

END IF;
  • Related