search
HomeDatabaseOracleExamples of how to create and execute stored procedures in Oracle

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];

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;

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;

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 [, ...])

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;

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;

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;

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!

Statement
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
Oracle: Exploring the Company's Mission and ValueOracle: Exploring the Company's Mission and ValueApr 26, 2025 am 12:06 AM

Oracle's mission is to "help people see the value of data", and its core values ​​include: 1) Customer first, 2) Integrity, 3) Innovation, and 4) Teamwork. These values ​​guide Oracle's strategic decision-making and business innovation in the market.

Oracle's Core Function: Providing Database SolutionsOracle's Core Function: Providing Database SolutionsApr 25, 2025 am 12:06 AM

Oracle Database is a relational database management system that supports SQL and object relational models to provide data security and high availability. 1. The core functions of Oracle database include data storage, retrieval, security and backup and recovery. 2. Its working principle involves multi-layer storage structure, MVCC mechanism and optimizer. 3. Basic usages include creating tables, inserting and querying data; advanced usages involve stored procedures and triggers. 4. Performance optimization strategies include the use of indexes, optimized SQL statements and memory management.

Using Oracle Software: Database Management and BeyondUsing Oracle Software: Database Management and BeyondApr 24, 2025 am 12:18 AM

In addition to database management, Oracle software is also used in JavaEE applications, data grids and high-performance computing. 1. OracleWebLogicServer is used to deploy and manage JavaEE applications. 2. OracleCoherence provides high-performance data storage and caching services. 3. OracleExadata is used for high performance computing. These tools allow Oracle to play a more diversified role in the enterprise IT architecture.

Oracle's Role in the Business WorldOracle's Role in the Business WorldApr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

Oracle Software in Action: Real-World ExamplesOracle Software in Action: Real-World ExamplesApr 22, 2025 am 12:12 AM

Oracle software applications in the real world include e-commerce platforms and manufacturing. 1) On e-commerce platforms, OracleDatabase is used to store and query user information. 2) In manufacturing, OracleE-BusinessSuite is used to optimize inventory and production planning.

Oracle Software: Applications and IndustriesOracle Software: Applications and IndustriesApr 21, 2025 am 12:01 AM

The reason why Oracle software shines in multiple fields is its powerful application and customized solutions. 1) Oracle provides comprehensive solutions from database management to ERP, CRM, SCM, 2) its solutions can be customized according to industry characteristics such as finance, medical care, manufacturing, etc. 3) Successful cases include Citibank, Mayo Clinic and Toyota, 4) The advantages lie in comprehensiveness, customization and scalability, but challenges include complexity, cost and integration issues.

Choosing Between MySQL and Oracle: A Decision GuideChoosing Between MySQL and Oracle: A Decision GuideApr 20, 2025 am 12:02 AM

Choosing MySQL or Oracle depends on project requirements: 1. MySQL is suitable for small and medium-sized applications and Internet projects because of its open source, free and ease of use; 2. Oracle is suitable for core business systems of large enterprises because of its powerful, stable and advanced functions, but at a high cost.

Oracle's Products: A Deep DiveOracle's Products: A Deep DiveApr 19, 2025 am 12:14 AM

Oracle's product ecosystem includes databases, middleware and cloud services. 1. OracleDatabase is its core product, supporting efficient data storage and management. 2. Middleware such as OracleWebLogicServer connects to different systems. 3. OracleCloud provides a complete set of cloud computing solutions.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools