原文参考:
组成:
- 声明部分(可选)
- 执行部分(必选)
- 异常处理(可选)
PL/SQL变量和常量
变量
格式:
variable_name datatype [NOT NULL := value ];
例子:
dept varchar2(10) NOT NULL := “HR Dept”;
指定变量值的两种方式:
1) variable_name:= value;
2)
SELECT column_name
INTO variable_name
FROM table_name
[WHERE condition];
变量范围:
- Local variables -定义在嵌套块里,不能被外部块访问
- Global variables - 定义在外部块里,可以供自己使用,也可以被其里面的嵌套块使用。
常量
格式:
constant_name CONSTANT datatype := VALUE;
例子:
salary_increase CONSTANT number (3) := 10;
pl/Sql Record 记录
定义和声明pl/Sql Record的几种方式:
语法格式 | 用途 |
TYPE record_type_name IS RECORD (column_name1 datatype, column_name2 datatype, ...); | Define a composite datatype, where each field is scalar. |
col_name table_name.column_name%type; | Dynamically define the datatype of a column based on a database column. |
record_name record_type_name; | Declare a record based on a user-defined type. |
record_name table_name%ROWTYPE; | Dynamically declare a record based on an entire row of a table. Each column in the table corresponds to a field in the record. |
语法格式 | 用途 |
record_name.col_name := value; | To directly assign a value to a specific column of a record. |
record_name.column_name := value; | To directly assign a value to a specific column of a record, if the record is declared using %ROWTYPE. |
SELECT col1, col2 INTO record_name.col_name1, record_name.col_name2 FROM table_name [WHERE clause]; | To assign values to each field of a record from the database table. |
SELECT * INTO record_name FROM table_name [WHERE clause]; | To assign a value to all fields in the record from a database table. |
variable_name := record_name.col_name; | To get a value from a record column and assigning it to a variable. |