Este conteúdo foi traduzido por máquina para sua conveniência e a Huawei Cloud não pode garantir que o conteúdo foi traduzido com precisão. Para exibir o conteúdo original, use o link no canto superior direito para mudar para a página em inglês.
Computação
Elastic Cloud Server
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Redes
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Gerenciamento e governança
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
Cloud Operations Center
Resource Governance Center
Migração
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Análises
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
IoT
IoT Device Access
Outros
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Segurança e conformidade
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Serviços de mídia
Media Processing Center
Video On Demand
Live
SparkRTC
Armazenamento
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Cloud Server Backup Service
Storage Disaster Recovery Service
Scalable File Service
Volume Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Bancos de dados
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Aplicações de negócios
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Data Lake Factory
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Distribuição de conteúdo e computação de borda
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Soluções
SAP Cloud
High Performance Computing
Serviços para desenvolvedore
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
Cloud Application Engine
MacroVerse aPaaS
KooPhone
KooDrive
Nesta página

Mostrar todos

Central de ajuda/ GaussDB(DWS)/ Perguntas frequentes/ Uso do banco de dados/ What Are the Differences Between Functions and Stored Procedures?

What Are the Differences Between Functions and Stored Procedures?

Atualizado em 2025-01-23 GMT+08:00

Functions and stored procedures are two common objects in database management systems. They have similarities and differences in implementing specific functions. Understanding their characteristics and application scenarios is important for properly designing the database structure and improving database performance.

Tabela 1 Differences between functions and stored procedures

Function

Stored procedures

Both can be used to implement specific functions. Both functions and stored procedures can encapsulate a series of SQL statements to complete certain specific operations.

Both can receive input parameters and perform corresponding operations based on the parameters.

The identifier of a function is FUNCTION.

The identifier of the stored procedure is PROCEDURE.

A function must return a specific value of the specified numeric type.

A stored procedure can have no return value, one return value, or multiple return values. You can use output parameters to return results or directly use the SELECT statement in a stored procedure to return result sets.

Functions are used to return single values, for example, a number calculation result, a string processing result, or a table.

Stored procedures are used for DML operations, for example, inserting, updating, and deleting data in batches.

  • Creating and Invoking a Function

    Create the emp table and insert data into the table. The table data is as follows:

    1
    2
    3
    4
    5
    6
    7
    8
    SELECT * FROM emp;
     empno | ename |   job    | mgr  |      hiredate       |   sal   |  comm  | deptno
    -------+-------+----------+------+---------------------+---------+--------+--------
      7369 | SMITH | CLERK    | 7902 | 1980-12-17 00:00:00 |  800.00 |        |     20
      7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 00:00:00 | 1600.00 | 300.00 |     30
      7566 | JONES | MANAGER  | 7839 | 1981-04-02 00:00:00 | 2975.00 |        |     20
      7521 | WARD  | SALESMAN | 7698 | 1981-02-22 00:00:00 | 1250.00 | 500.00 |     30
    (4 rows)
    

    Create the emp_comp function to accept two numbers as input and return the calculated value.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    CREATE OR REPLACE FUNCTION emp_comp (
        p_sal           NUMBER,
        p_comm          NUMBER
    ) RETURN NUMBER
    IS
    BEGIN
        RETURN (p_sal + NVL(p_comm, 0)) * 24;
    END;
    /
    

    Run the SELECT command to invoke the function:

    1
    2
    3
    4
    5
    6
    7
    8
    SELECT ename "Name", sal "Salary", comm "Commission", emp_comp(sal, comm) "Total Compensation" FROM emp;
     Name  | Salary  | Commission | Total Compensation
    -------+---------+------------+--------------------
     SMITH |  800.00 |            |           19200.00
     ALLEN | 1600.00 |     300.00 |           45600.00
     JONES | 2975.00 |            |           71400.00
     WARD  | 1250.00 |     500.00 |           42000.00
    (4 rows)
    
  • Creating and Invoking a Stored Procedure

    Create the MATCHES table and insert data into the table. The table data is as follows:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    SELECT * FROM MATCHES;
     matchno | teamno | playerno | won | lost
    ---------+--------+----------+-----+------
           1 |      1 |        6 |   3 |    1
           7 |      1 |       57 |   3 |    0
           8 |      1 |        8 |   0 |    3
           9 |      2 |       27 |   3 |    2
          11 |      2 |      112 |   2 |    3
    (5 rows)
    

    Create the stored procedure delete_matches to delete all matches that a specified player participates in.

    1
    2
    3
    4
    5
    6
    CREATE PROCEDURE delete_matches(IN p_playerno INTEGER) 
    AS 
    BEGIN
       DELETE FROM MATCHES WHERE playerno = p_playerno;
    END;
    /
    

    Invoke the stored procedure delete_matches.

    1
    CALL delete_matches(57);
    

    Query the MATCHES table again. The returned result indicates that the data of the player whose playerno is 57 has been deleted.

    1
    2
    3
    4
    5
    6
    7
    8
    SELECT * FROM MATCHES;
     matchno | teamno | playerno | won | lost
    ---------+--------+----------+-----+------
          11 |      2 |      112 |   2 |    3
           8 |      1 |        8 |   0 |    3
           1 |      1 |        6 |   3 |    1
           9 |      2 |       27 |   3 |    2
    (4 rows)
    

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Conteúdo selecionado

Envie o conteúdo selecionado com o feedback