12. Stored Procedure
A Stored Procedure is a set of SQL statements that performs an operation or sequence of operations. Think of it as a complete program stored on the database server.
Example Use Case: Automated Order Processing
A procedure might be used to finalize an order
Update the
Inventorytable (UPDATE).Insert a new record into the
Salestable (INSERT).Commit the transaction.
Oracle PL/SQL Stored Procedure
CREATE OR REPLACE PROCEDURE Finalize_Order ( ... )
-
Purpose: Defines a stored procedure in Oracle.
-
CREATE OR REPLACE: Creates a new procedure or replaces an existing one with the same name. -
Finalize_Order: The name of the stored procedure. -
(...): The parameter list—used to pass input values into the procedure.
Each line defines a parameter:
-
p_product_id: product being sold. -
p_quantity: how many units are sold. -
p_customer_id: the buyer’s ID.
-
-
IN→ means data flows into the procedure (input-only parameter). -
NUMBER→ defines the datatype.
IS
Marks the start of the procedure body in PL/SQL.
Similar to saying “beginning of declaration and code section.”
Use
SET SERVEROUTPUT ON;in SQL Developer or SQL*Plus to see the output.
BEGIN
Marks the start of executable statements.
All SQL logic (update, insert, etc.) goes between
BEGINandEND.
Use
SET SERVEROUTPUT ON;in SQL Developer or SQL*Plus to see the output.
Update Inventory
Reduces stock quantity by the amount sold.
Inventory→ table name.SET quantity = quantity - p_quantity→ subtracts ordered quantity from available stock.WHERE product_id = p_product_id→ ensures only that product’s row is updated.
Insert Sale Record
Adds a new row into the Sales table for this transaction.
sales_seq.NEXTVAL→ uses a sequence namedsales_seqto generate a unique sale ID automatically.SYSDATE→ system date/time (when the sale happens).
Commit Transaction
-
Makes the changes permanent in the database (update + insert).
-
Without
COMMIT, changes wouldn’t persist after the procedure ends.
Success Message
-
Prints a message to the SQL console (for debugging/confirmation).
-
DBMS_OUTPUTis an Oracle package for displaying messages. -
Use
SET SERVEROUTPUT ON;in SQL Developer or SQL*Plus to see the output.
Full code:
To Run it:
Fl Key Characteristics
Purpose: To execute a sequence of DML (
INSERT,UPDATE,DELETE) or DDL (CREATE,ALTER) commands, or complex retrieval tasks.Return Value: Can return zero, one, or multiple result sets (tables of data). It can also return a single numeric value (an exit code or status code) to indicate success or failure.
Execution: Executed using the
EXECorEXECUTEcommand.Transactional Control: Procedures can manage transactions (using
BEGIN TRAN,COMMIT,ROLLBACK), making them ideal for ensuring multi-step processes either fully succeed or completely fail.
Comments
Post a Comment