编者按:
人,一半是天使,一半是魔鬼。
最好的学习是实践加上看官方文档。官方文档中的代码例更是精华和重点所在。
IT行业如此,编程如此,Oracle PL/SQL的学习更是如此。
本系列以摘自《Database PL/SQL Language Reference》的PL/SQL代码例为主进行介绍。
【免责声明】本公众号文章仅代表个人观点,与任何公司无关。
编辑|SQL和数据库技术(ID:SQLplusDB)
Oracle PL/SQL例
Oracle PL/SQL编程基础 Oracle PL/SQL例2:处理查询的结果行(基础循环) Oracle PL/SQL例3:使用双引号 Oracle PL/SQL例4:文字(Literals)换行的处理 Oracle PL/SQL例5:注释 Oracle PL/SQL例6:声明变量/常量 Oracle PL/SQL例7:%TYPE 属性
例1:使用名字引用标识符
代码语言:javascript复制DECLARE
a INTEGER; -- Declaration
BEGIN
a := 1; -- Reference with simple name
END;
/
例2:标识符的可见范围
代码语言:javascript复制-- Outer block:
DECLARE
a CHAR; -- Scope of a (CHAR) begins
b REAL; -- Scope of b begins
BEGIN
-- Visible: a (CHAR), b
-- First sub-block:
DECLARE
a INTEGER; -- Scope of a (INTEGER) begins
c REAL; -- Scope of c begins
BEGIN
-- Visible: a (INTEGER), b, c
NULL;
END; -- Scopes of a (INTEGER) and c end
-- Second sub-block:
DECLARE
d REAL; -- Scope of d begins
BEGIN
-- Visible: a (CHAR), b, d
NULL;
END; -- Scope of d ends
-- Visible: a (CHAR), b
END; -- Scopes of a (CHAR) and b end
/
例3:引用子程序
代码语言:javascript复制
CREATE OR REPLACE PROCEDURE check_credit (credit_limit NUMBER) AS
rating NUMBER := 3;
FUNCTION check_rating RETURN BOOLEAN IS
rating NUMBER := 1;
over_limit BOOLEAN;
BEGIN
IF check_credit.rating <= credit_limit THEN -- reference global variable
over_limit := FALSE;
ELSE
over_limit := TRUE;
rating := credit_limit; -- reference local variable
END IF;
RETURN over_limit;
END check_rating;
BEGIN
IF check_rating THEN
DBMS_OUTPUT.PUT_LINE
('Credit rating over limit (' || TO_CHAR(credit_limit) || '). '
|| 'Rating: ' || TO_CHAR(rating));
ELSE
DBMS_OUTPUT.PUT_LINE
('Credit rating OK. ' || 'Rating: ' || TO_CHAR(rating));
END IF;
END;
/
输出:
代码语言:javascript复制SQL> set serverout on
SQL> BEGIN
2 check_credit(1);
3 END;
4 /
Credit rating over limit (1). Rating: 3
PL/SQL 过程已成功完成。
例4:不同单元的引用
代码语言:javascript复制SQL> DECLARE
2 PROCEDURE p
3 IS
4 x VARCHAR2(1);
5 BEGIN
6 x := 'a'; -- Assign the value 'a' to x
7 DBMS_OUTPUT.PUT_LINE('In procedure p, x = ' || x);
8 END;
9
10 PROCEDURE q
11 IS
12 x VARCHAR2(1);
13 BEGIN
14 x := 'b'; -- Assign the value 'b' to x
15 DBMS_OUTPUT.PUT_LINE('In procedure q, x = ' || x);
16 END;
17
18 BEGIN
19 p;
20 q;
21 END;
22 /
In procedure p, x = a
In procedure q, x = b
PL/SQL 过程已成功完成。
代码语言:javascript复制SQL> <<echo>>
2 DECLARE
3 x NUMBER := 5;
4
5 PROCEDURE echo AS
6 x NUMBER := 0;
7 BEGIN
8 DBMS_OUTPUT.PUT_LINE('x = ' || x);
9 DBMS_OUTPUT.PUT_LINE('echo.x = ' || echo.x);
10 END;
11
12 BEGIN
13 echo;
14 END;
15 /
x = 0
echo.x = 0
PL/SQL 过程已成功完成。