PL/SQL控制结构

--1.条件分支语句
--语法
IF condition THEN
statements
[ELSIF condition THEN
statements]
[ELSE 
    statements]
END IF;

--2.CASE
--语法
CASE selector
WHEN expression1 THEN sequence_of_statements1;
WHEN expression2 THEN sequence_of_statements2;
...
WHEN expressionN THEN sequence_of_statementsN;
[ELSE sequence_of_statementsN+1]
END CASE;

CASE
WHEN search_condition1 THEN sequence_of_statements1;
WHEN search_condition2 THEN sequence_of_statements2;
...
WHEN search_conditionN THEN sequence_of_statementsN;
[ELSE sequence_of_statementsN+1]
END CASE;

--3.循环
--基本循环
--语法
LOOP
    statements1;
    ...
    EXIT [WHEN condition];
END LOOP;

--DEMO
DECLARE
i INT:=1;
BEGIN
    LOOP
        INSERT INTO temp VALUSE(i);
        EXIT WHEN i=10;
        i:=i+1;
    END LOOP;
END;
/

--WHILE循环
--语法
WHILE condition LOOP
    statements1;
    statements2;
    ...
END LOOP;

--DEMO
DECLARE
    i INT:=1;
BEGIN
    WHILE i<=10 LOOP
        INSERT INTO temp VALUES(i);
        i:=i+1;
    END LOOP;
END;
/

--FOR循环
--语法
FOR counter IN [REVERSE]
    lower_bound..upper_bound LOOP
    statements1;
    statements2;
    ...
END LOOP;

--DEMO
BEGIN
    FOR i IN REVERSE 1..10 LOOP
        INSERT INTO temp VALUES(i);
    END LOOP;
END;
/

--嵌套循环和标号
--DEMO
DECLARE
    result INT;
BEGIN
    <<outer>>
    FOR i IN 1..100 LOOP
        <<inner>>
        FOR j IN 1..10 LOOP
            result:=i*j;
            EXIT outer WHEN result=100;
            EXIT WHEN result = 50;
            dbms_output.put_line('inner:'||result);
        END LOOP inner;
        dbms_output.put_line('outer:'||result);
    END LOOP outer;
    dbms_output.put_line('dbms_output.put_line:'||result);
END;
/
        
4.顺序控制语句
--GOTO
--语法
GOTO label_name;

--DEMO
DECLARE
    i INT:=1;
BEGIN
    LOOP
        INSERT INTO temp VALUES(i);
        IF i=9 THEN
            GOTO end_loop;
        END IF;
        i:=i+1;
    END LOOP;
    <<end_loop>>
    dbms_output.put_line('循环结束');
END;
/
    
--NULL
--DEMO
DECLARE
    v_sal emp.sal%TYPE;
    v_ename emp.ename%TYPE;
BEGIN
    SELECT ename,sal INTO v_ename,v_sal
    FROM emp
    WHERE empno=&eno;
    IF v_sal<3000 THEN
        UPDATE emp SET comm=sal*0.1 WHERE ename=v_ename;
    ELSE
        NULL;
    END IF;
END;
/

posted on 2012-08-21 17:39  wean  阅读(431)  评论(0编辑  收藏  举报

导航