Home > Database > Oracle > body text

Examples of how to create and execute stored procedures in Oracle

PHPz
Release: 2023-04-25 17:27:02
Original
4676 people have browsed it

Oracle is a very powerful database management system that has many advanced functions and features, of which stored procedures are one of them. A stored procedure is a set of predefined SQL statements for database operations that can be stored in the database for later call use.

In Oracle, stored procedures are written in PL/SQL, a language that combines SQL and programming. PL/SQL has strong data manipulation capabilities and process control capabilities, and can easily write efficient stored procedures.

Benefits of stored procedures

The main benefit of stored procedures is that it can increase the execution efficiency of the database and reduce network communication overhead. Because the stored procedure has been pre-compiled and optimized, there is no need to repeatedly parse and optimize it during execution, and can be directly called for execution. In addition, stored procedures can also implement dynamic operations through parameters, which not only simplifies the code but also avoids risks such as SQL injection.

Creation and execution of stored procedures

The following describes how to create and execute stored procedures in Oracle.

Create a stored procedure

In Oracle, you need to use the CREATE PROCEDURE statement to create a stored procedure. The syntax is as follows:

CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] parameter_type [, ...])]
[IS | AS]
BEGIN
      pl/sql_code_block;
END [procedure_name];
Copy after login

Among them:

  • CREATE PROCEDURE: statement that creates a stored procedure.
  • OR REPLACE: Optional parameter. If this parameter is specified, it means that the created stored procedure will be replaced if it already exists.
  • procedure_name: The name of the stored procedure.
  • parameter_name: Optional input and/or output parameters used to specify the input and output of the stored procedure.
  • parameter_type: The type of parameter, which can be a data type such as VARCHAR2, NUMBER, or a cursor type, such as SYS_REFCURSOR.
  • IS | AS: Optional parameter, used to specify the language type of the stored procedure, IS represents the start (PL/SQL block), AS represents the end (PL/SQL block).
  • pl/sql_code_block: PL/SQL code block, which contains the specific logic implementation of the stored procedure.

The following example code demonstrates how to create a simple stored procedure that accepts two parameters and outputs their sum:

CREATE OR REPLACE PROCEDURE add_nums(
    num1 IN NUMBER,
    num2 IN NUMBER,
    sum OUT NUMBER
)
IS
BEGIN
    sum := num1 + num2;
END add_nums;
Copy after login

Execute the stored procedure

In In Oracle, the EXECUTE or EXECUTE IMMEDIATE statement is required to execute a stored procedure. For example, to execute the above sample program, you can use the following statement:

DECLARE
    result NUMBER;
BEGIN
    add_nums(10, 20, result);
    DBMS_OUTPUT.PUT_LINE('The sum is: ' || result);
END;
Copy after login

Here we use the DECLARE statement to declare the variable result that needs to be used, and call the add_nums stored procedure and output the result to the screen.

Parameter type

In a stored procedure, parameters can be input parameters, output parameters or bidirectional parameters.

  • Input parameters: Specify the input of the stored procedure.
  • Output parameters: Specify the output of the stored procedure.
  • Bidirectional parameters: can be input or output.

The method of declaring the parameter type is as follows:

(param_name [IN | OUT | IN OUT] param_type [, ...])
Copy after login

In this declaration, [IN | OUT | IN OUT] is an optional parameter, used to specify the type of the parameter. If the parameter type is not specified, it defaults to the IN type, that is, the input parameter.

Sample code:

CREATE OR REPLACE PROCEDURE my_proc (
    num IN NUMBER,
    str IN OUT VARCHAR2,
    cur OUT SYS_REFCURSOR
)
IS
BEGIN
    -- 逻辑实现
END my_proc;
Copy after login

In the above code, we declare a stored procedure my_proc containing three parameters. The first parameter num is the input parameter, and the second parameter str is bidirectional. Parameters, the third parameter cur is the output parameter.

Record set processing

When using stored procedures to operate data, it is often necessary to return a query result list. Oracle provides two types of recordsets: cursors and PL/SQL tables.

Cursor

A cursor is a data structure that returns a result set, which can traverse query results. Cursors can be explicit or implicit. Explicit cursors require declaring a cursor variable and opening and closing it in code. Implicit cursors are automatically created and managed by Oracle.

Here is a stored procedure that demonstrates how to use a cursor:

CREATE OR REPLACE PROCEDURE get_employee(
    id_list IN VARCHAR2,
    emp_cur OUT SYS_REFCURSOR
)
IS
BEGIN
    OPEN emp_cur FOR 'SELECT * FROM employees WHERE id IN (' || id_list || ')';
END get_employee;
Copy after login

In this example, we declare a stored procedure get_employee with two parameters, which accepts a comma-separated list of employees The ID list is used as an input parameter and a cursor emp_cur containing the selected employee information is returned.

PL/SQL table

PL/SQL table is an array-like data structure that can store a set of values. PL/SQL tables have many practical applications in stored procedures, such as passing a set of data to a stored procedure, etc.

In Oracle, PL/SQL tables can be declared and used in stored procedures, such as the following code:

CREATE OR REPLACE PACKAGE my_package
IS
    TYPE num_list IS TABLE OF NUMBER INDEX BY PLS_INTEGER;

    PROCEDURE sum_nums(nums IN num_list, sum OUT NUMBER);
END my_package;

CREATE OR REPLACE PACKAGE BODY my_package
IS
    PROCEDURE sum_nums(nums IN num_list, sum OUT NUMBER)
    IS
        total NUMBER := 0;
    BEGIN
        FOR indx IN 1 .. nums.COUNT LOOP
            total := total + nums(indx);
        END LOOP;
        sum := total;
    END sum_nums;
END my_package;
Copy after login

Here, we create a package named my_package, which declares A PL/SQL table type named num_list and a stored procedure sum_nums that uses that type. sum_nums accepts an argument of type num_list and calculates their sum.

Conclusion

In Oracle, stored procedures are one of the important tools for maintaining databases. They have efficient execution capabilities and dynamics. We can also use stored procedures to let it execute some business logic instead of just executing a single SQL statement, which can improve reusability and maintainability. Because they can be stored in a database and shared and accessed by multiple applications or processes. There are many benefits to using stored procedures, and it is difficult to cover them all in just a short article, but we believe that as long as you have an in-depth understanding and application, you will benefit a lot in actual work.

The above is the detailed content of Examples of how to create and execute stored procedures in Oracle. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template