How to Create A Stored Procedure In Oracle?

14 minutes read

To create a stored procedure in Oracle, follow these steps:

  1. Open a SQL command line or Oracle SQL Developer tool.
  2. Connect to your Oracle database using valid credentials.
  3. Select the database where you want to create the stored procedure.
  4. Begin the procedure creation with the CREATE PROCEDURE statement, followed by the procedure name.
  5. Specify any input parameters for the procedure by using the IN keyword followed by the parameter name and data type.
  6. Specify any output parameters for the procedure by using the OUT keyword followed by the parameter name and data type.
  7. Declare any local variables needed within the procedure using the DECLARE statement.
  8. Begin the body of the procedure by using the BEGIN keyword.
  9. Write the necessary SQL statements and logic required for the procedure's functionality.
  10. Execute the END keyword to signal the end of the procedure's code block.
  11. Optionally, you can include exception handling code using the EXCEPTION keyword followed by specific error handling instructions.
  12. Finalize the procedure creation by executing a forward slash / or any other command that executes the SQL statement.


Here's an example of a stored procedure in Oracle:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
CREATE PROCEDURE get_employee_details (emp_id IN NUMBER, emp_name OUT VARCHAR2, emp_salary OUT NUMBER)
IS
    emp_address VARCHAR2(100);
BEGIN
    SELECT name, salary, address INTO emp_name, emp_salary, emp_address
    FROM employees
    WHERE id = emp_id;
    
    -- Additional logic or data manipulation can be done here
    
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        emp_name := 'Employee not found';
        emp_salary := 0;
        
END;
/


This example demonstrates a procedure named get_employee_details, which takes an employee ID as input and returns the employee's name and salary as output parameters. It also provides error handling if the specified employee ID is not found in the employees table.

Best Oracle Books to Read in 2024

1
Oracle PL/SQL by Example (The Oracle Press Database and Data Science)

Rating is 5 out of 5

Oracle PL/SQL by Example (The Oracle Press Database and Data Science)

2
Oracle Database 12c DBA Handbook (Oracle Press)

Rating is 4.9 out of 5

Oracle Database 12c DBA Handbook (Oracle Press)

3
Oracle Database Administration: The Essential Refe: A Quick Reference for the Oracle DBA

Rating is 4.8 out of 5

Oracle Database Administration: The Essential Refe: A Quick Reference for the Oracle DBA

4
Oracle DBA Mentor: Succeeding as an Oracle Database Administrator

Rating is 4.7 out of 5

Oracle DBA Mentor: Succeeding as an Oracle Database Administrator

5
OCA Oracle Database SQL Exam Guide (Exam 1Z0-071) (Oracle Press)

Rating is 4.6 out of 5

OCA Oracle Database SQL Exam Guide (Exam 1Z0-071) (Oracle Press)

6
Oracle Database 12c SQL

Rating is 4.5 out of 5

Oracle Database 12c SQL

7
Oracle Autonomous Database in Enterprise Architecture: Utilize Oracle Cloud Infrastructure Autonomous Databases for better consolidation, automation, and security

Rating is 4.4 out of 5

Oracle Autonomous Database in Enterprise Architecture: Utilize Oracle Cloud Infrastructure Autonomous Databases for better consolidation, automation, and security


What is the syntax to define a stored procedure in Oracle?

To define a stored procedure in Oracle, you can use the following syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
CREATE [OR REPLACE] PROCEDURE procedure_name
(parameter1 [IN | OUT | IN OUT] data_type,
 parameter2 [IN | OUT | IN OUT] data_type,
 ...
)
IS
  -- Declaration section
BEGIN
  -- Implementation section
END;
/


In the syntax, the CREATE PROCEDURE statement is used to define the stored procedure. The [OR REPLACE] option allows you to modify an existing stored procedure with the same name.


After the procedure name, you define one or more parameters with their data types. The parameters can be IN, OUT, or IN OUT depending on whether they are used to pass values into the procedure, receive values from the procedure, or both.


Inside the procedure, you have the declaration section where you can declare local variables and cursors.


The implementation section contains the actual code of the stored procedure.


Finally, the END; keyword marks the end of the stored procedure definition, and the / symbol is used to execute the CREATE PROCEDURE statement.


What is the significance of PL/SQL in creating stored procedures in Oracle?

PL/SQL (Procedural Language/Structured Query Language) is a powerful programming language used in Oracle Database to create stored procedures, functions, packages, triggers, and various database objects. It has several significant aspects in creating stored procedures in Oracle:

  1. Enhanced Procedural Capabilities: PL/SQL provides extensive procedural language features like loops, conditionals, variables, error handling, and exception handling. This allows developers to create complex and interactive logic within stored procedures.
  2. Integration with SQL: PL/SQL seamlessly integrates with SQL, allowing developers to embed SQL queries and data manipulation statements within the procedural code. This integration facilitates data retrieval, modification, and manipulation operations, making stored procedures more versatile and efficient.
  3. Improved Performance: PL/SQL is a compiled language, and stored procedures written in PL/SQL are compiled and executed within the database engine. This eliminates the overhead of network communication when executing SQL statements individually and improves performance by reducing network latency.
  4. Security and Data Integrity: Oracle's PL/SQL supports robust security mechanisms, including fine-grained access control and privileges. Stored procedures can be defined with specific access and execution privileges, ensuring data security and maintaining data integrity by controlling who can access and modify the data.
  5. Code Reusability and Maintainability: PL/SQL allows developers to create reusable code blocks in the form of functions and procedures. These code blocks can be called multiple times from different parts of the application, promoting code reuse and reducing redundancy. Additionally, as stored procedures are stored and managed within the database, they are easier to maintain and upgrade.
  6. Transaction Control: PL/SQL provides control over transaction management through explicit COMMIT and ROLLBACK statements. This allows developers to ensure data consistency and perform complex transactional operations within a single stored procedure.
  7. Exception Handling: PL/SQL offers comprehensive exception handling capabilities, enabling developers to catch and handle exceptions effectively within stored procedures. This ensures graceful error handling and recovery, enhancing the resilience of the application.


Overall, PL/SQL plays a crucial role in simplifying procedural development, optimizing performance, ensuring data security, and enhancing application maintainability in Oracle Database.


What is a stored procedure in Oracle?

A stored procedure in Oracle is a named, pre-compiled block of SQL code that is stored in the database and can be executed repeatedly. It is stored as a database object, similar to tables or views, and can be called and executed by other programs or applications.


Stored procedures are typically used to perform complex database operations, such as data manipulation, transaction control, and business logic computations. They can accept input parameters, perform computations and transformations on data, and return results or modify database tables based on the defined logic.


Stored procedures in Oracle offer advantages such as improved performance, code reusability, security, and simplification of complex business logic operations. They can also be used to encapsulate commonly performed tasks, reducing the need to write redundant code.


How to schedule the execution of a stored procedure in Oracle?

In Oracle, you can schedule the execution of a stored procedure using the Oracle Scheduler feature. Here is how you can do it:

  1. Create a job class: A job class defines the attributes and behavior of a group of jobs. You can create a job class using the DBMS_SCHEDULER.CREATE_JOB_CLASS procedure.
  2. Create a program: A program defines what needs to be executed as part of the job. In this case, the program will be the stored procedure you want to execute. You can create a program using the DBMS_SCHEDULER.CREATE_PROGRAM procedure.
  3. Create a schedule: A schedule defines the time when the job should be executed. You can specify the execution frequency and other parameters using the DBMS_SCHEDULER.CREATE_SCHEDULE procedure.
  4. Create a job: A job combines the program, schedule, and other attributes to define the complete job. You can create a job using the DBMS_SCHEDULER.CREATE_JOB procedure.
  5. Enable and run the job: After creating the job, you need to enable it using the DBMS_SCHEDULER.ENABLE procedure. The job will be automatically executed according to the specified schedule.


Here is an example script that shows how to schedule the execution of a stored procedure called "my_procedure":

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
-- Step 1: Create job class
BEGIN
  DBMS_SCHEDULER.CREATE_JOB_CLASS(
    job_class_name => 'my_job_class',
    resource_consumer_group => 'default_consumer_group',
    service => 'SYS$BACKGROUND',
    logging_level => DBMS_SCHEDULER.LOGGING_OFF);
END;
/

-- Step 2: Create program
BEGIN
  DBMS_SCHEDULER.CREATE_PROGRAM(
    program_name => 'my_program',
    program_type => 'STORED_PROCEDURE',
    program_action => 'my_procedure',
    program_enabled => TRUE);
END;
/

-- Step 3: Create schedule
BEGIN
  DBMS_SCHEDULER.CREATE_SCHEDULE(
    schedule_name => 'my_schedule',
    repeat_interval => 'FREQ=DAILY;BYHOUR=12;BYMINUTE=0;BYSECOND=0',
    start_date => SYSTIMESTAMP,
    end_date => NULL);
END;
/

-- Step 4: Create job
BEGIN
  DBMS_SCHEDULER.CREATE_JOB(
    job_name => 'my_job',
    program_name => 'my_program',
    job_class => 'my_job_class',
    schedule_name => 'my_schedule',
    enabled => TRUE,
    auto_drop => FALSE);
END;
/

-- Step 5: Enable and run job
BEGIN
  DBMS_SCHEDULER.ENABLE('my_job');
  DBMS_SCHEDULER.RUN_JOB('my_job');
END;
/


This example schedules the execution of the "my_procedure" stored procedure every day at 12:00 PM. Adjust the schedule parameters and procedure name according to your requirements.


Note: You need appropriate privileges (e.g., "CREATE JOB", "CREATE PROGRAM", etc.) to execute the required procedures.


What is the importance of naming conventions for stored procedures in Oracle?

Naming conventions for stored procedures in Oracle are important for several reasons:

  1. Readability and understandability: Clear and consistent naming conventions make it easier for developers, administrators, and other stakeholders to understand the purpose and functionality of a stored procedure. This improves code readability, making it more maintainable and reducing the likelihood of errors or misunderstandings.
  2. Consistency and standardization: Naming conventions ensure that all stored procedures within a database or organization follow a standard format. This promotes consistency across the codebase, simplifying the process of locating, managing, and modifying stored procedures. It also helps developers easily identify and understand the purpose of a stored procedure, even if they are unfamiliar with the specific code.
  3. Clarity and documentation: A well-chosen name can act as a self-documenting element of the code. A properly named stored procedure can provide insights into its functionality, parameters, and expected behavior without needing to dive into the code itself. This is especially useful when working in large databases or when collaborating with other developers.
  4. Scalability and manageability: Proper naming conventions facilitate effective management of stored procedures, particularly when dealing with large databases or complex systems. It becomes easier to search for, sort, and organize stored procedures based on their names, which can be important for maintenance, troubleshooting, or system-wide changes.
  5. Avoiding conflicts and errors: Following consistent naming conventions helps avoid naming conflicts with other objects or procedures, both within the same database and across different databases. Additionally, standardized names reduce the likelihood of typographical errors or misspellings when referring to or executing stored procedures.


Overall, adopting and adhering to proper naming conventions for stored procedures in Oracle enhances code organization, readability, maintainability, and collaboration within a development team or organization. It promotes efficient database management and improves the overall quality and usability of the system.


What is the role of a stored procedure in database performance optimization?

A stored procedure in database performance optimization plays a crucial role in improving the overall performance and efficiency of database operations. Here are some key roles of a stored procedure in this context:

  1. Reduced Network Traffic: By executing complex database operations on the server-side, stored procedures help minimize network traffic. The data manipulation or retrieval tasks are performed within the database server, reducing the amount of data transferred between the client and server.
  2. Improved Execution Plan: Stored procedures allow database administrators to define and optimize the execution plan, which is a sequence of steps that the database engine follows to execute the requested operation. By precompiling and saving the execution plan, stored procedures can reduce the query processing time, resulting in faster execution.
  3. Reduced Latency: With stored procedures, repetitive or frequent queries can be stored and executed as a single block of code. This helps in reducing the latency caused by the overhead of establishing a connection with the database server for each individual query.
  4. Enhanced Security: Stored procedures provide an additional layer of security by allowing access control at the procedure level. By granting or denying permissions on stored procedures, database administrators can enforce security policies and ensure that only authorized users can execute specific operations.
  5. Code Reusability: Stored procedures promote code reusability, as they can be called from multiple applications or different parts of an application. This eliminates the need to duplicate code, reduces the chance of errors, and simplifies maintenance tasks.
  6. Reduced Database Load: By encapsulating complex logic and calculations within stored procedures, the database load is minimized. Instead of performing calculations at the application level, the database engine handles the computation, leading to better utilization of database resources.
  7. Optimized Indexing: Stored procedures can be designed to utilize appropriate indexes efficiently. By specifying the optimal execution plan and index usage within the procedure, database performance can be significantly improved, resulting in faster data retrieval and manipulation.


Overall, stored procedures serve as a valuable tool in database performance optimization by optimizing query execution, reducing network traffic, enhancing security, improving code reusability, and minimizing database load.

Facebook Twitter LinkedIn Telegram

Related Posts:

To execute stored procedures with parameters in Oracle, you can follow the steps below:Connect to the Oracle database using a client tool such as SQL Developer or SQL*Plus. Ensure that you have the necessary privileges to execute the stored procedure. Open a n...
Stored procedures in MySQL are powerful tools that allow you to create reusable and modular pieces of code. They are essentially a group of SQL statements that are stored and executed on the server side.To create a stored procedure in MySQL, you need to use th...
To call a stored procedure in CakePHP, you can use the $this->Model->query() method. Here are the steps to follow:Open the model file where you want to call the stored procedure. This can be found in app/Model directory. Inside the model file, create a f...