MySQL support IF(),IFNULL(),CASE,LOOP,LEAVE ITRATE,REPEAT and WHILE constructs flow control within stored programs.
(A) IF() syntax
if () is an IF function not IF statement.
if exprt is true <> 0 and exprt<> NULL),
IF() returns exprt2. Otherwise, it returns expr3.
Example
mysql> SELECT if (1 > 2,2,3);
3
mysql> SELECT IF (1<2, 'YES', 'NO');
'yes'
mysql> SELECT IF(STRCMP('text','text'),'no','yes');
'no'
(B) IFNULL()
syntex
if expr1 is NOT NULL, IFNULL() returns expr1, otherwise it returns expr2. example
mysql> SELECT IFNULL(1,0);
1
mysql> SELECT IFNULL(NULL,10);
10
mysql> SELECT IFNULL(1/0,10);
10
mysql> SELECT IFNULL(1/0, 10);
10
mysql>SELECT IFNULL(1/0,10);
10
(C) CASE
Syntex
Here, casevalue is an expression. This value is compared to the whenvalue expression in eachWHEN clause
untill one of them is equal. when an equal whenvalue is found, the corresponding THEN clause statmentlist executes, if there is one.
Each statmentlist consists of one or more mysql statement;an empty statementlist is not permitted.
To handle situations where no value is matched by any WHEN clause, use an ELSE containing an empty
BEGIN............ END block, as shown in this example.
example
BEGIN
DECLARE V INT DEFAULT 1;
CASE V
WHEN 2 THEN SELECT V;
WHEN 3 THEN SELECT 0;
ELSE
BEGIN
END;
END CASE;
END;
(D)loop
Syntex
LOOP implements a simple loop construct, enabling repeated execution of the statements list, which consists of one or more statements, each terminated by a semicolon (;). the statement whithin the loop are repeated untill the loop is terminated. Usually this is done by using LEAVE statement.
if we neglect to include a loop termination statement LEAVE, this result in an infinite loop
LOOP statement can be labelled.
Example
BEGIN DECLARE PI INT DEFAULT 1;
label1: LOOP
SET P1 = P1 +1;
IF P1<10 THEN
ITERATE label1;
END IF;
LEAVE label1;
END LOOP label1;
END ;
0 Comments