1. 程式人生 > 實用技巧 >MySQL中的流程控制

MySQL中的流程控制

使用 if、case、loop、leave、iterate、repeat、while 語句來控制流程。

1、if 語句

            IF i_staff_id =2 THEN
                 SET @x1 = @x1 + d_amont;
            ELSE
                set @x2 = @x2 +d_amount;
            end if;

2、case 語句

CASE 
    WHEN i_staff_id = 2 THEN
        set @x1 = @x1 + d_amount
    
ELSE set @x2 = @x2 + d_amount END CASE;

或者

CASE i_staff_id 
    WHEN 2 THEN
        set @x1 = @x1 + d_amount
    ELSE
        set @x2 = @x2 + d_amount
END CASE;

3、loop 語句(通常和 leave 語句一起使用)

4、leave 語句

CREATE PROCEDURE actor_insert ( ) BEGIN
    
    SET @x = 0;
    ins :LOOP   
        SET
@x = @x + 1 IF @x = 100 THEN LEAVE ins; END IF; INSERT INTO actor ( first_name, last_name ) VALUES( 'Test', '201' ); END LOOP label; END;
call actor_insert();
select count(*) from actor where first_name='Test'

5、iterate 語句

CREATE PROCEDURE actor_insert() BEGIN
    
    SET @x = 0;
    ins :LOOP
            
        SET @x = @x + 1;
        IF @x = 10 THEN
        LEAVE ins;
            
        END IF;
        INSERT INTO actor ( actor_id, first_name, last_name )
        VALUES( @x + 200, 'Test', @x );
        
    END LOOP ins;

END;
call actor_insert();
select actor_id,first_name,last_name from actor where first_name='Test';

6、REPATE 語句

    REPEAT
    FETCH cur_payment INTO i_staff_id, d_amount;
      if i_staff_id =2 THEN
                SET @x1 = @x1 + d_amont;
            ELSE
                set @x2 = @x2 +d_amount;
            end if;
    
    UNTIL 0 END REPEAT;

7、while 語句

CREATE PROCEDURE loop_demo() BEGIN
    
    SET @x = 1,@x1 = 1;
    REPEAT
            
            SET @x = @x + 1;
    UNTIL @x > 0 END REPEAT;
    WHILE @x < 0 DO
            
            SET @x1 = @x1 + 1;
        
    END WHILE;

END;
call loop_demo();