PL/SQL in Oracle

Table of contents

1. Introduction

2. Basic structure

Ⅰ. A structure containing only the execution part

Ⅱ. If a block has a statement and execution part, but no exception handling part

3. Notes

3.1. Single-line comments:

3.2. Multi-line comments:

3.3. Documentation comments:

4. Character set

5. Data type

6. Constants and variables

6.1. Define the format of constants:

6.2. Format of defining variables:

6.3. Variable initialization


1. Introduction

      PL/SQL is the abbreviation of Procedural Language /Structured Query Language. It is a programming language in Oracle. It integrates the advantages of SQL and adds programming elements such as process and loop structure, conditional judgment and exception handling. PL/SQL is widely used to develop database objects such as stored procedures, triggers, and functions . These objects can further encapsulate business logic, improve database performance, and reduce network traffic.

2. Basic structure

      Its basic structure includes statement area, execution area and exception area, as follows:

DECLARE
-- 此处进行变量或者常量的声明:常声明一些变量、常量、用户定义的数据类型以及游标等
-- 这一部分可选,如不需要可以不写

BEGIN
-- 主程序体,在这里可以加入各种合法语句
-- 此处编写 PL/SQL 代码进行业务逻辑处理

EXCEPTION
-- 此处对可能发生的异常进行处理,当程序中出现错误时执行这一部分

END;--主程序体结束

       Among them, DECLARE (optional) is used to declare all variables, constants, cursors, subroutines and exceptions used in the program. The statement between BEGIN and END is the main body of the program and is used to implement business logic. In an EXCEPTION block, events that cause program errors or other problems can be caught or handled.

      Therefore, it can be seen from the above structure that it contains three basic parts: declarative section, executable section and exception handling section . Among them, only the execution part is required, and the other two parts are optional .

Notice:

The semicolon at the end of the structure is required.

If there is no declaration section, the structure begins with the BEGN keyword. If there is no exception handling section, the keyword EXCEPTION will be omitted, and the END keyword is followed by a semicolon to end the definition of the block.

Ⅰ. A structure containing only the execution part

The definition looks like this:

BEGIN
*执行部分*/
END;

In fact, in PL/SQL, we can also use anonymous blocks and named blocks to organize and manage code .

An anonymous block refers to a PL/SQL code block without a name, which can be directly entered and executed in the SQL*Plus command window or other tools . The above is the anonymous block expression, such as the following example:

BEGIN
DBMS_OUTPUT.PUT_LINE('Hello, world!');
END;

Here, BEGIN and END define an anonymous block in which the PL/SQL code simply outputs a message.

Ⅱ. If a block has a statement and execution part, but no exception handling part

It is defined as follows:

DECLARE
/体声明部分*/
BEGIN
/*执行部分*/
END;

 The following example shows a PL/SQL code block with declaration and execution sections, but no exception handling section:

DECLARE
   v_emp_id employees.employee_id%TYPE := 100; 
   v_salary employees.salary%TYPE;
BEGIN
   SELECT salary INTO v_salary FROM employees WHERE employee_id = v_emp_id;
   dbms_output.put_line('The salary of the employee with ID ' || v_emp_id || ' is ' || v_salary);
END;
/

     In the above example, I created a variable called v_emp_id which holds the employee ID. I then use a SELECT statement to look up the salary of the employee with the given ID from the employees table and store the result in the v_salary variable. Finally, use the PUT_LINE method in the DBMS_OUTPUT package to output the results to the screen.

Remark:

In the actual programming process, the exception handling part is very important to ensure the stable operation of the program and data security, so it is recommended not to omit it.

In the above description of the structure definition that only contains the execution part, it is mentioned that there are anonymous blocks. Here is a brief description of the named blocks!

A named block is a PL/SQL code block with a name, usually used to store complex business logic and reusable program segments . Named blocks can be created by CREATE PROCEDURE or CREATE FUNCTION statement . For example:

CREATE OR REPLACE PROCEDURE show_salary (EMP_ID NUMBER) IS
   v_salary employees.salary%TYPE;
BEGIN
   SELECT salary INTO v_salary FROM employees WHERE employee_id = EMP_ID;
   dbms_output.put_line('The salary of the employee with ID ' || EMP_ID || ' is ' || v_salary);
END;

      Here I use CREATE PROCEDURE to create a block named show_salary, which is used to query the salary information of the specified employee and output the result. Named blocks usually have more complex structures and functions, such as parameters, return values, cursors, etc.

hint:

Anonymous blocks and named blocks can be distinguished clearly, and they can be clearly distinguished. In actual work and application, most of the cases use named blocks, that is, we use them to create functions, store them, etc.

3. Notes

PL/SQL code can use three different types of comments:

3.1. Single-line comments:

Everything starting with two dashes (--) until the end of the line is considered a comment. For example:

 -- This is a single-line comment

Suppose you have the following PL/SQL block:

DECLARE
V_Department CHAR(3);
V_Course     NUMBER;
BEGIN
    INSERT INTO classes (department,course)
         VALUES(V_Department,V_Course);
END;

To make this block easier for users to understand, annotate them as follows:

DECLARE
V_Department  CHAR(3);   --保存3个字符的变量
                         --系代码
V_Course NUMBER;         --保存课程号的变量
BEGIN
--插入一条记录
   INSERT INTO classes(department,course)
        VALUES (V_Department,V_Course);
END;

hint:

If a comment exceeds one line, it must use a double hyphen (--) at the beginning of each line.

3.2. Multi-line comments:

Starting with /*, ending with */, everything in between is considered a comment. It can span multiple lines. This is the same as the C language usage. For example:

  /* This is a multi-line comment, which can extend over 
      multiple lines until it is closed with a */ symbol. */

--如下PL/SQL块多行注释应用
DECLARE
v_Department CHAR(3);  /*体保存三个字符的变量,系代码*/
V_course     NUMBER;  /*体保存课程号的变量。*/
BEGIN
   /*插入一条记录*/
INSERT INTO classes (department,course)
     VALUES(V_Department,V_Course);
END;

3.3. Documentation comments:

Start with /**, can span multiple lines, mainly used for documentation generation tools. For example:

 /**
    * This is a documentation comment for a PL/SQL program.
    **/

Remark:

In Oracle, Document Comment (Document Comment) was introduced from PL/SQL 9.0 and is currently supported in all major Oracle database versions. Therefore, from Oracle 9i to the latest version (such as Oracle 19c), it is possible to use documentation comments in PL/SQL programs.

The above comments can be used to record important information in PL/SQL programs, such as program purpose, author, creation date, etc., and improve code readability and maintainability. The way to apply annotations is to insert the corresponding annotation symbol and follow the annotation content at the place where annotation needs to be added. For example, in the following PL/SQL program segment, I add comments:

DECLARE
   -- 声明一个变量来保存员工 ID
   v_emp_id employees.employee_id%TYPE := 100;
   -- 声明一个变量来保存员工工资
   v_salary employees.salary%TYPE;

BEGIN
   -- 使用给定 ID 检索员工的工资
   SELECT salary INTO v_salary FROM employees
   WHERE employee_id = v_emp_id;

   -- 将工资信息打印到输出控制台
   dbms_output.put_line('The salary of the employee with ID ' || v_emp_id || ' is ' || v_salary);
END;

I explained variable declarations and query statements with single-line comments. These comments help other colleagues better understand how the code works, and they provide helpful hints and instructions when the code needs to be modified or extended later.

suggestion:

Cultivate the good habit of adding comments while writing code, especially the code developed by yourself, before it is fully launched, you have to go through code debugging and environmental testing. If you find a problem, you can find the corresponding location and change it in time, which provides a good solution for subsequent work Help, especially the addition of special fields, script optimization, and comments are very necessary!

4. Character set

The character set of PL/SQL includes the following types:

  • 1. ASCII character set: This is the most basic character set in PL/SQL, including all common English letters, numbers and symbols.
  • 2. Unicode character set: Unicode is an international coding standard that supports almost all letters, symbols and characters in the world, including Chinese, Japanese, Korean, etc. In Oracle, PL/SQL can use the Unicode character set to represent and process text data in various languages.
  • 3. Local character set of the operating system: This is the character set used by the operating system by default. It is usually dominated by the local language. For example, it may be GB18030 or UTF-8 on the system in mainland China, and it may be Big5 in Taiwan or Hong Kong. PL/SQL programs can use the local character set of the operating system to interact with the operating system, and perform operations such as file input and output.
  • 4. User-defined character sets: In some cases, PL/SQL programs need to use specific character sets to process text data, such as processing special XML or JSON data formats. The Oracle database provides some tools and interfaces that allow users to customize character sets and perform related operations.

The character set of PL/SQL in Oracle is very rich, which can meet the needs of various languages ​​and application scenarios.

5. Data type

PL/SQL data types include the following types:

  • 1. Numeric: including integers, real numbers, decimal numbers with precision, etc. The most commonly used type is the NUMBER type, which is used to represent arbitrary precision values.
  • 2. Character (Character): including fixed-length CHAR type and variable-length VARCHAR2 type. Among them, the CHAR type needs to specify a specific length, while the VARCHAR2 type can specify any length within a certain range.
  • 3. Date and Time (Date and Time): A data type used to represent date, time, and a combination of date and time. The most common of these is the DATE type, which can store dates and times from 4712 BC to 9999 AD.
  • 4. Boolean (Boolean): A data type used to represent logical true or false. There are only two values: TRUE and FALSE.
  • 5. Large object type (Large Object): used to represent large binary data and text data. Including BLOB and CLOB two types, BLOB is used to store binary data, and CLOB is used to store Unicode text data.
  • 6. PL/SQL Tables: It is one of the special data types of the PL/SQL language. It is a collection type similar to an array and can store multiple data items of the same type. PL/SQL tables are divided into index tables and association tables, corresponding to arrays based on numeric subscripts and string subscripts respectively.
  • 7. Record type (Record): used to represent complex data types similar to structures. A record type is a data structure consisting of a set of fields, each of which can have its own data type.
  • 8. Other data types: including REFCURSOR type, which can be used to return a cursor object; BINARY_INTEGER type, used for high-performance numerical operations, etc.

In fact, the data types of PL/SQL are basically the same as those of SQL statements , including Numeric, Character, Date and Time, etc. However, there are some special data types in PL/SQL, such as PL/SQL Tables and Record , which are one of the special data types of PL/SQL language, and in SQL statements does not exist in .

Also, while PL/SQL data types are largely the same as SQL statement data types, there may be differences in their usage and behavior . For example, in SQL statements, for numeric types with decimals, when using the ROUND function for rounding, it may be rounded to an even number (that is, the "banker's rounding" rule), while in PL/SQL, you can specify the ROUND function The second parameter to control the rounding method.

Therefore, although the data types of PL/SQL in Oracle are basically the same as the data types of SQL statements, you need to pay attention to their nuances and different behavioral characteristics when using them.

6. Constants and variables

Usually constants and variables in PL/SQL can be defined using the DECLARE keyword. Its format is as follows:

6.1. Define the format of constants:

 DECLARE
      常量名 CONSTANT 数据类型 [:= 初始值];

Once a constant is defined, its value will not change in future use. Some fixed sizes are best defined as constants in order to prevent someone from changing them. As shown in the following example:

DECLARE
      PI CONSTANT NUMBER(10,2) := 3.14;
BEGIN
      DBMS_OUTPUT.PUT_LINE('PI的值为:' || PI);
END;

   In the example, I define a constant named PI, whose data type is NUMBER(10,2), which is a numerical type with at most 10 digits before the decimal point and at most 2 digits after the decimal point. At the same time, we also gave it an initial value of 3.14. Between BEGIN and END, I output the value of PI using the DBMS_OUTPUT.PUT_LINE function.

6.2. Format of defining variables:

DECLARE
      变量名 数据类型 [:= 初始值];

As shown in the following example:

 DECLARE
      name VARCHAR2(20) := 'John';
      age NUMBER(3) := 30;
BEGIN
      DBMS_OUTPUT.PUT_LINE(name || '的年龄是' || age || '岁。');
END;

   In the above example, I defined two variables name and age, and their data types are VARCHAR2(20) and NUMBER(3), that is, a string type with a maximum length of 20 and a numeric type, and give them at the same time Initial values ​​'John' and 30 are given. Between BEGIN and END, I used the DBMS_OUTPUT.PUT_LINE function to output the string "The age of name is age." This string references the values ​​​​of the two variables name and age.

Notice:

In Oracle, all constants and variables must be defined before they can be used. At the same time, you can also directly specify the default value in the declaration part. If you do not specify the default value, the system will automatically assign them the NULL value.

6.3. Variable initialization

PL/SQL variables can be assigned initial values ​​by initialization. Variable initialization can be done when the variable is declared, or before the variable is assigned . Generally, you need to declare the variable and specify the data type of the variable before initializing the variable . Here is a simple example:

DECLARE
   name VARCHAR2(20);
BEGIN
   name := 'John';
   DBMS_OUTPUT.PUT_LINE(name);
END;

I defined a string variable called name and set its data type to VARCHAR2(20). After the variable declaration, I use an assignment statement to initialize the variable to 'John', and then use the DBMS_OUTPUT.PUT_LINE function to output the value of the variable.

But in some cases, when the variable is declared, it must be initialized, otherwise it will cause errors or logic problems. For example, here is an example that demonstrates a constant variable that can only be assigned a value during initialization:

DECLARE
   PI CONSTANT NUMBER(10,2) := 3.14;
BEGIN
   DBMS_OUTPUT.PUT_LINE(PI);
END;

In the example, I define a constant called PI, its data type is NUMBER(10,2), and set its initial value to 3.14. Since PI is a constant, it must be initialized when it is declared, otherwise it will cause a compilation error.

Summarize:

Variable initialization is a very basic and common operation in PL/SQL. It can ensure the stability and reliability of the variables in the program, and improve the execution efficiency and quality of the code.

Guess you like

Origin blog.csdn.net/m0_71406734/article/details/131110846