Oracle Series Eleven: PL/SQL

PL (Procedural Language)/SQL is a programming language used to write objects such as stored procedures, triggers, and functions of the Oracle database. It also supports object-oriented programming (OOP) and dynamic SQL, which can improve development efficiency and application maintainability.

PL/SQL combines the characteristics of SQL statements and general programming languages ​​to realize complex data operations and business logic. Compared with SQL statements, PL/SQL has more powerful data processing functions and higher execution efficiency, and can be processed on the server side, reducing network communication overhead and facilitating maintenance and reuse.

1. PL/SQL statement block composition

A PL/SQL statement block consists of three main parts: statement part, execution part, and exception handling .

DECLARE
   Declaration statements
BEGIN
   Executable statements
EXCEPTION
   Exception-handling statements
END;
  • Declaration section (Declaration Section): This section is used to declare objects such as variables, constants, cursors, subroutines, and can define types and tables. A declaration section DECLAREstarts with a keyword and BEGINends with a keyword.
  • Execution Section: This section contains the main body of the PL/SQL code and is used to perform specific operations, such as SQL statements such as SELECT, UPDATE, DELETE, or control statements ( IF-THEN, LOOP, WHILE-DOetc.). The execution section BEGINbegins with a keyword and ENDends with .
  • Exception Handling Section (Exception Handling Section): This section is used to capture and handle errors that may occur when the program is running. In the execution part, if an exception occurs, it will jump to the exception handling part for corresponding processing. The exception handling section EXCEPTIONbegins with the keyword and ends with END.

2. Declaration and use of variables

By using variables, PL/SQL programs can be made more flexible and readable.

(1) Variable declaration

In PL/SQL, a variable needs to be declared and its type specified before it can be used.

  • declare an integer variable
DECLARE
  my_variable INTEGER;
BEGIN
  -- 代码块
END;
  • declare a character variable
DECLARE
  my_variable VARCHAR2(50);
BEGIN
  -- 代码块
END;
  • Declare a date variable
DECLARE
  my_variable DATE;
BEGIN
  -- 代码块
END;
  • declare a cursor variable
DECLARE
  my_cursor SYS_REFCURSOR;
BEGIN
  -- 代码块
END;

(2) Variable assignment

Variables can be used in code blocks and can be assigned, calculated and compared:

  • assignment operation
DECLARE
  my_variable INTEGER := 10;
BEGIN
  -- 代码块
END;
  • calculation operation
DECLARE
  x INTEGER := 5;
  y INTEGER := 3;
  result INTEGER;
BEGIN
  result := x + y; -- 计算x和y的和
END;
  • comparison operation
DECLARE
  x INTEGER := 5;
  y INTEGER := 3;
  result BOOLEAN;
BEGIN
  result := (x > y); -- 比较x是否大于y
END;

3. Control Statements

(1) Branch statement

Branching statements in PL/SQL include IF-THEN-ELSEstatements and CASEstatements.

  • IF-THEN-ELSEThe statement executes different statement blocks according to the condition
  • CASEThe statement executes different blocks of statements depending on the value of the variable

eg IF-THEN-ELSE statement:

DECLARE
   salary NUMBER := 5000;
BEGIN
   IF salary > 10000 THEN
      dbms_output.put_line('High Salary');
   ELSIF salary > 5000 THEN
      dbms_output.put_line('Medium Salary');
   ELSE
      dbms_output.put_line('Low Salary');
   END IF;
END;

eg CASE statement:

DECLARE
   grade CHAR(1) := 'A';
BEGIN
   CASE grade
      WHEN 'A' THEN dbms_output.put_line('Excellent');
      WHEN 'B' THEN dbms_output.put_line('Good');
      WHEN 'C' THEN dbms_output.put_line('Fair');
      ELSE dbms_output.put_line('Needs Improvement');
   END CASE;
END;

(2) Loop statement

  • LOOPbasic cycle
LOOP 
END LOOP;

e.g

BEGIN
X:=0;
LOOP
X:=X+1;
EXIT WHEN X>=3;
DBMS_OUTPUT.PUT_LINE('X:'||X);
END LOOP;
END;
  • WHILEcycle
WHILE expression LOOP
END LOOP;

e.g

BEGIN
X:=0;
WHILE X<=3 LOOP
X:=x+1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('X='||X);
END;
  • FORcycle
FOR counter IN [REVERSE] start_value..end_value LOOP
END LOOP;

e.g

-- 递增量只能是1
FOR I IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('I='||I);
END LOOP;

4. Exception handling

Exception handling in PL/SQL is a mechanism for catching and handling errors that occur during program execution. When an exception occurs, control is transferred to the exception handling section, which contains the block of code that handles the exception. Exception handling can improve the robustness and reliability of the program, avoiding unexpected program crashes and data loss.

PL/SQL uses BEGIN...EXCEPTION...ENDstatement blocks to handle exceptions. The code between BEGINand EXCEPTIONis called "protected code". If an exception occurs during the execution of this code, it will jump to the EXCEPTION block to execute the corresponding exception handling logic.

Typically, an exception-handling block logs the exception and takes some action to allow the program to continue or exit properly. For example, you can display error messages to the user, roll back uncommitted transactions, close open files, and so on.

There are many predefined exception types in PL/SQL. You can use the EXCEPTION WHEN statement to handle specific types of exceptions, or you can customize the exception types and manually raise exceptions through the RAISE statement.

(1) System abnormality

System exceptions in PL/SQL refer to exceptions thrown by the Oracle database engine during program execution. Common PL/SQL system exceptions are as follows:

  • NO_DATA_FOUND: This exception is thrown when the SELECT statement does not retrieve any data.
  • TOO_MANY_ROWS: This exception is thrown when the SELECT statement returns multiple rows of data.
  • DUP_VAL_ON_INDEX: This exception is thrown when trying to insert duplicate values ​​into a column or primary key with a unique constraint.
  • INVALID_CURSOR: This exception is thrown when trying to use an invalid cursor.
  • TIMEOUT_ON_RESOURCE: This exception is thrown when waiting for a resource to time out, such as waiting for a lock or I/O operation to complete.
  • STORAGE_ERROR: This exception is thrown when PL/SQL memory space is insufficient.
  • PROGRAM_ERROR: This exception is thrown when a compiler or runtime error occurs.
  • OTHERS: When there is no matching exception handler, all unhandled exceptions will be converted to this exception.

e.g

DECLARE
TEST VARCHAR2(10);
BEGIN
SELECT X INTO TEST FROM DETAIL.T_JBXX WHERE ID=1;
DBMS_OUTPUT.PUT_LINE('TEST IS:'||TEST);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO_DATA_FOUND');
END;

(2) Custom exceptions

In PL/SQL, you can use custom exceptions to handle errors that may occur when the program is running.

e.g

DECLARE
TNAME VARCHAR2(20);
E EXCEPTION; /*声明异常*/
BEGIN
SELECT X INTO TNAME FROM DETAIL.T_JBXX WHERE ID=32334;
IF TNAME<>'TOM' THEN
RAISE E; /*抛出异常*/
END IF;
DBMS_OUTPUT.PUT_LINE(TNAME);
EXCEPTION  /*异常处理*/
WHEN E THEN
DBMS_OUTPUT.PUT_LINE('ERROR NOT TOM');
END;

Guess you like

Origin blog.csdn.net/apr15/article/details/130373232