Sub topic 3
Creating and replacing a stored procedure
This chapter assumes you can write an anonymous PL/SQL block, run basic DML, and use SQL*Plus, SQLcl, or SQL Developer. Your schema needs the CREATE PROCEDURE privilege. A stored procedure is a named PL/SQL block that Oracle compiles and keeps in the database. Any session with permission can call it by name.
The shape of a procedure
A stored procedure is an anonymous block with a header on top. The header gives it a name and a parameter list. The general form is:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [mode] datatype [DEFAULT value], ...)]
AS -- IS means the same thing
-- local declarations go here (no DECLARE keyword)
BEGIN
-- executable statements
EXCEPTION
-- optional handlers
END [procedure_name];Three details differ from the anonymous blocks you already know:
ASorISreplacesDECLARE. Local variables, cursors, and types go betweenASandBEGIN. If you have none, leave that section empty.- Parameter data types have no length or precision. Write
NUMBERandVARCHAR2, notVARCHAR2(30). Oracle rejects a constraint in a parameter type (PLS-00103). To tie a parameter to a column, use an anchored type such asemployees.employee_id%TYPE. - A procedure with no parameters has no parentheses at all.
CREATE PROCEDURE purge_temp AS ...is correct, andpurge_temp()in the header is a syntax error.
A worked example
This procedure raises one employee's salary by a percentage. It uses the employees table from the HR sample schema.
CREATE OR REPLACE PROCEDURE raise_salary (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
) AS
BEGIN
UPDATE employees
SET salary = salary * (1 + p_percent / 100)
WHERE employee_id = p_employee_id;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Employee not found: ' || p_employee_id);
END IF;
END raise_salary;
/The pieces, in order:
CREATE OR REPLACE PROCEDURE raise_salarynames the procedure. The name lives in your schema's namespace, shared with tables, views, functions, and packages.p_employee_id IN employees.employee_id%TYPEtakes its type from the column. If the column's definition changes later, the parameter follows. Thep_prefix keeps the parameter from colliding with a column name inside SQL. Without it,WHERE employee_id = employee_idcompares the column to itself.p_percent IN NUMBER DEFAULT 10makes the second argument optional. A caller can omit it. TheINmode and calling notation are covered in the next two chapters.SQL%ROWCOUNTholds the number of rows affected by the most recent DML statement. Here it detects a missing employee, because anUPDATEthat matches nothing is not an error.RAISE_APPLICATION_ERROR(-20001, ...)stops the procedure and sends a user-defined error to the caller. Error numbers must fall between -20000 and -20999.END raise_salary;repeats the name. This is optional, but it helps when you read long procedures.- The
/on its own line tells SQL*Plus, SQLcl, and SQL Developer to send the buffered text to the database. The slash is a client convention and is not part of the PL/SQL language. Without it, the tool keeps waiting for more input, because the semicolons inside the body do not end the statement.
A successful run prints Procedure created. A run with a compile error prints Warning: Procedure created with compilation errors. Treat that second message as a failure. The next section explains why.
What happens when you run CREATE
Oracle stores the procedure's source text and its compiled form in the data dictionary. A compile error does not stop the statement from taking effect. The object is stored anyway, with status INVALID. If it replaced a working version, the working version is gone.
Replacing instead of dropping
CREATE OR REPLACE has these properties:
- A plain
CREATEfails if the name is taken. You getORA-00955: name is already used by an existing object. This applies even when the existing object is a table or a function, not a procedure. OR REPLACEswaps the definition in place. It works only when the existing object is also a procedure. Using it on a name that belongs to a table still raises ORA-00955.- Grants survive. Any
EXECUTEprivilege already granted on the procedure stays in place.DROP PROCEDUREfollowed byCREATE PROCEDUREdiscards those grants, and you would have to re-issue them. - Dependents are invalidated. Other stored code that calls the procedure is marked
INVALID, and Oracle recompiles it on its next use. Chapter 10 covers this in detail. - Running sessions are not interrupted. A session already executing the old version finishes with it. New calls use the new version.
Checking what was stored
After creating a procedure, confirm its status and read back its source from the dictionary views:
SELECT object_name, object_type, status, last_ddl_time
FROM user_objects
WHERE object_name = 'RAISE_SALARY';
SELECT line, text
FROM user_source
WHERE name = 'RAISE_SALARY'
AND type = 'PROCEDURE'
ORDER BY line;Dictionary names are stored in uppercase unless you created them with quoted identifiers, so compare against 'RAISE_SALARY'. If status is INVALID, query user_errors, or run SHOW ERRORS PROCEDURE raise_salary in SQL*Plus or SQLcl. The line and position columns point into the source you just read from user_source.
Running the procedure and managing the transaction
A procedure does not commit unless you write COMMIT inside it. The caller owns the transaction. This lets one procedure be reused as a step in a larger unit of work. A quick test looks like this:
SET SERVEROUTPUT ON
BEGIN
raise_salary(100, 5);
END;
/
SELECT employee_id, salary
FROM employees
WHERE employee_id = 100;
ROLLBACK;The SELECT shows the raised salary because it runs in the same session and transaction. The ROLLBACK undoes the change, which is useful when you test against shared sample data. In SQL*Plus and SQLcl, EXEC raise_salary(100, 5) is shorthand for the same anonymous block. It is a client command, so it does not work from application code.
If you call raise_salary(9999, 5), no employee matches. The procedure raises ORA-20001 with the message Employee not found: 9999. Raising an error from a procedure does not roll back anything automatically beyond the failed statement. Chapter 8 covers how errors and transactions interact.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Tool hangs after the last `END;` | The closing `/` is missing | Add `/` on its own line |
| `PLS-00103` near a parameter type | A length such as `VARCHAR2(30)` is in the parameter list | Remove the length, or use `%TYPE` |
| `ORA-00955` | `CREATE` without `OR REPLACE`, or the name belongs to a different object type | Add `OR REPLACE`, or choose another name |
| `ORA-01031: insufficient privileges` | The schema lacks `CREATE PROCEDURE` | Ask a DBA for the grant |
| Update seems to do nothing, no error | `WHERE` clause compares a column to a parameter with the same name | Prefix parameters, for example `p_` |
| Other code breaks after you replace the procedure | Dependents are invalid, or the new version has compile errors | Check `user_objects` and `user_errors` |
Summary of the creation rules
- Use
CREATE OR REPLACE PROCEDURE name (params) AS ... BEGIN ... END;and finish with/in command-line tools. - Declare parameter types without sizes, and anchor them with
%TYPEwhere a column defines them. - Treat the "created with compilation errors" warning as a failed deployment. The procedure is stored but invalid.
- Prefer
OR REPLACEover drop and create, so existing grants survive. - Leave transaction control to the caller unless the procedure's purpose is to commit.
Exercise
You run CREATE OR REPLACE PROCEDURE raise_salary with a misspelled column name. SQL*Plus prints "Warning: Procedure created with compilation errors." Is the previous working version still callable? How do you find the problem?
Show answer
No. The new definition replaced the old one and was stored with status INVALID, so a call such as raisesalary(100, 5) fails (for example with PLS-00905 in an anonymous block). To find the problem, run SHOW ERRORS PROCEDURE raisesalary or query USERERRORS WHERE name = 'RAISESALARY' AND type = 'PROCEDURE' ORDER BY sequence. Fix the source, run CREATE OR REPLACE again, and confirm that USER_OBJECTS shows status VALID.
Exercise
A colleague has EXECUTE on your procedure. You want to change its body. Should you DROP and CREATE it, or use CREATE OR REPLACE, and why?
Show answer
Use CREATE OR REPLACE. Dropping the procedure also removes the EXECUTE grant, so your colleague's calls would fail until you re-grant it. CREATE OR REPLACE keeps the existing grants and replaces only the definition.