query_script_if_else

QueryScript Flow Control: if-else statement

SYNOPSIS

if (expression)
  statement;
[else
  statement;]

DESCRIPTION

if-else is a flow control branching structure. It makes for a condition test based on a given expression.

When the expression holds true, the statement (or block of statements) following the if statement are executed. The else clause is optional, and it's statement(s) are executed when the expression does not hold true.

There is no built-in elseif clause. However, a chained if-else if-else statement is valid.

Empty statements are not allowed in QueryScript. However, empty blocks are, and a if or else clause may use an empty block statement, or by the do-nothing pass statement.

EXAMPLES

Simple if-else condition:

set @x := 17;
if (@x mod 2 = 0)
  SELECT 'even' AS answer;
else
  SELECT 'odd' AS answer;

DELETE statement as expression:

set @country := 'USA';
if (DELETE FROM world.Country WHERE Code = @country)
{
  -- We don't have foreign keys on these tables; do a manual drill down:
  DELETE FROM world.City WHERE CountryCode = @country;
  DELETE FROM world.CountryLanguage WHERE CountryCode = @country;
}

Using if to break out of a while loop:

CREATE TEMPORARY TABLE test.numbers (n INT UNSIGNED NOT NULL PRIMARY KEY);
INSERT INTO test.numbers (n) VALUES (17);

set @n := 0;
while (@n < 20)
{
  if (INSERT IGNORE INTO test.numbers (n) VALUES (@n))
  {
  }
  else
  {
    break;
  }
  set @n := @n + 1;
}
SELECT @n AS inserted_up_to_this_value;

+---------------------------+
| inserted_up_to_this_value |
+---------------------------+
|                        17 |
+---------------------------+

SEE ALSO

while, expressions

AUTHOR

Shlomi Noach
 
common_schema documentation