无名块:未命名的程序块
命名块:指过程,函数,包和触发器
定义部分:用于定义变量,常量,游标,触发器,复合数据类型
执行部分:用于实现应用模块功能,包含了要执行的PL/SQL语句和SQL语句
异常处理部分:用于处理执行部分可能出现的运行错误
[DECLARE
... --定义部分]
BEGIN
... --执行部分
[EXCEPTION
... --异常处理部分]
END;
-------------------------------------
DECLARE
a NUMBER;
BEGIN
a:=1+2;
DBMS_OUTPUT.PUT_LINE('1+2='||a);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('出现异常')
END;
/
条件分支语句:
DECLARE
a1 number := 100;
a2 number := 200;
BEGIN
IF a1>a2 THEN
DBMS_OUTPUT.PUT_LINE('a1 is larger than a2');
ELSIF a1=a2 THEN
DBMS_OUTPUT.PUT_LINE('a1 is equal to a2')
ELSE
DBMS_OUTPUT.PUT_LINE('a1 is smaller than a2');
ENDIF;
END;
/
------------------------------------------------------------------------------------
DECLARE
grade CHAR(1) := 'B';
appraisal VARCHAR2(20);
BEGIN
appraisal :=
CASE grade
WHEN 'A' THEN '优'
WHEN 'B' THEN '良'
WHEN 'C' THEN '中'
WHEN 'D' THEN '及格'
WHEN 'F' THEN '不及格'
ELSE '没有这样的等级'
DBMS_OUTPUT.PUT_LINE('Grade'||grade||'is'||appraisal);
END;
/
循环语句:
DECLARE
total number := 0;
salary number := 1800;
BEGIN
LOOP
total := total + salary;
EXIT WHEN total > 2500
END LOOP;
DBMS_OUTPUT.PUT_LINE('total salary is'||total);
END;
/
----------------------------------------------------------------------------
DECLARE
total number := 0;
salary number := 1800;
BEGIN
WHILE total<2500 LOOP
total := total + salary;
END LOOP;
DBMS_OUTPUT.PUT_LINE('total salary is'||total);
END;
/
---------------------------------------------------------------------------
DELARE
I INTEGER;
BEGIN
FOR I IN REVERSE 1..3 LOOP
DBMS_OUTPUT.PUT_LINE(I);
END LOOP;
END;
/