纸上得来终觉浅,绝知此事要躬行。计算机编程是工程,必须多动手实践!
1. 最简单的PL/SQL程序(Basic Block Structure)
SQL> BEGIN
2 NULL;
3 END;
4 /
PL/SQL procedure successfully completed.
2. 还能再简单吗?不行!比如,去掉null语句,会怎么样呢?
SQL> BEGIN
2
3 END;
4 /
END;
*
ERROR at line 3:
ORA-06550: line 3, column 1:
PLS-00103: Encountered the symbol "END" when expecting one of the following:
( begin case declare exit for goto if loop mod null pragma
raise return select update while with <an identifier>
<a double-quoted delimited-identifier> <a bind variable> <<
continue close current delete fetch lock insert open rollback
savepoint set sql execute commit forall merge pipe purge
3. 执行脚本文件
1)将以下语句保存为Hello_world.sql文件
SET SERVEROUTPUT ON SIZE UNLIMITED
BEGIN
dbms_output.put_line('Hello World.');
END;
/
2)执行该文件
SQL> @'D:\2.学无止境\DWBI\Oracle12cPLSQLCode\Chapter3\hello_world.sql'
Hello World.
PL/SQL procedure successfully completed.
4. PL/SQL中可输入单行或多行注释
-- This is a single-line comment.
/* This is a multiple-line comment.
Style and indentation should follow your company standards. */
5. 替换变量默认为数字,如果输入字符,需使用单引号,否则报错。
SQL> BEGIN
2 dbms_output.put_line('['||&input||']');
3 END;
4 /
Enter value for input: 123
old 2: dbms_output.put_line('['||&input||']');
new 2: dbms_output.put_line('['||123||']');
[123]
PL/SQL procedure successfully completed.
SQL> /
Enter value for input: abc
old 2: dbms_output.put_line('['||&input||']');
new 2: dbms_output.put_line('['||abc||']');
dbms_output.put_line('['||abc||']');
*
ERROR at line 2:
ORA-06550: line 2, column 27:
PLS-00201: identifier 'ABC' must be declared
ORA-06550: line 2, column 1:
PL/SQL: Statement ignored
6. Oracle支持使用会话变量(绑定变量),它们与匿名PL/SQL块中的替换变量相似。它们的不同之处在于:会话变量在数据库连接或数据库会话的上下文中有内存范围(占用内存空间)。
(Oracle also lets you use session (or bind) variables, which are similar to substitution variables in anonymous PL/SQL blocks. Session variables differ from substitution variables because they have a memory scope in the context of any connection or database session.)
SQL> VARIABLE bind_variable VARCHAR2(20)
SQL> BEGIN
2 :bind_variable:='HelloPL/SQL world!';
3 dbms_output.put_line('['||:bind_variable||']');
4 END;
5 /
[HelloPL/SQL world!]
PL/SQL procedure successfully completed.
SQL> col :bind_variable for a20
SQL> SELECT :bind_variable FROM dual;
:BIND_VARIABLE
--------------------
HelloPL/SQL world!
注意:在SQL中使用绑定变量时,其名称前要加冒号。