Creates a stored procedure.
Syntax
CREATE [OR REPLACE] PROCEDURE name [ (parameters) ]
[
IMMUTABLE
| STABLE
| VOLATILE
| DETERMINISTIC
| [ NOT ] LEAKPROOF
| CALLED ON NULL INPUT
| RETURNS NULL ON NULL INPUT
| STRICT
| [ EXTERNAL ] SECURITY INVOKER
| [ EXTERNAL ] SECURITY DEFINER
| AUTHID DEFINER
| AUTHID CURRENT_USER
| PARALLEL { UNSAFE | RESTRICTED | SAFE }
| COST execution_cost
| ROWS result_rows
| SET configuration_parameter
{ TO value | = value | FROM CURRENT }
...]
{ IS | AS }
[ PRAGMA AUTONOMOUS_TRANSACTION; ]
[ declarations ]
BEGIN
statements
END [ name ];Description
CREATE PROCEDURE creates a stored procedure. CREATE OR REPLACE PROCEDURE either creates a new stored procedure or replaces an existing definition.
If you specify a schema name, the stored procedure is created in the specified schema. Otherwise, it is created in the current schema.
Two stored procedures in the same schema can share a name if they have different input argument types. This is called overloading.
Overloading of standalone stored procedures is a feature of PolarDB for PostgreSQL (Compatible with Oracle) and is not compatible with Oracle databases.
CREATE OR REPLACE PROCEDURE cannot change the name or argument types of an existing stored procedure — doing so creates a new, distinct stored procedure instead. To change the types of OUT parameters, delete the stored procedure first and then recreate it.
Parameters
| Parameter | Description |
|---|---|
name | The identifier of the stored procedure. |
parameters | A list of parameter values. |
declarations | Variable, cursor, type, or subprogram declarations. Subprogram declarations must appear after all other variable, cursor, and type declarations. |
statements | SPL program statements. The BEGIN...END block can contain an EXCEPTION section. |
IMMUTABLE | STABLE | VOLATILE | Informs the query optimizer about the procedure's behavior. Specify at most one. Default is VOLATILE. See Volatility attributes. |
DETERMINISTIC | A synonym for IMMUTABLE. |
[ NOT ] LEAKPROOF | A LEAKPROOF procedure has no negative effects and reveals no information about the values used to call the stored procedure. |
CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT | Controls behavior when NULL arguments are passed. Default is CALLED ON NULL INPUT. See NULL-handling attributes. |
[ EXTERNAL ] SECURITY DEFINER | The procedure runs with the privileges of the user who created it. This is the default. The EXTERNAL keyword is accepted for SQL conformance but has no effect. |
[ EXTERNAL ] SECURITY INVOKER | The procedure runs with the privileges of the user who calls it. The EXTERNAL keyword is accepted for SQL conformance but has no effect. |
AUTHID DEFINER | A synonym for [EXTERNAL] SECURITY DEFINER. When the AUTHID clause is omitted or AUTHID DEFINER is specified, the rights of the stored procedure owner are used to determine access privileges to database objects. |
AUTHID CURRENT_USER | A synonym for [EXTERNAL] SECURITY INVOKER. |
PARALLEL { UNSAFE | RESTRICTED | SAFE } | Controls whether the procedure can run in parallel mode. Default is UNSAFE when the clause is omitted. See Parallel attributes. |
COST execution_cost | A positive number estimating the execution cost in units of cpu_operator_cost. If the procedure returns a set, this is the cost per returned row. Higher values prompt the planner to call the procedure less frequently. |
ROWS result_rows | A positive number estimating the number of rows the planner expects the procedure to return. Valid only when the procedure is declared to return a set. Default is 1000. |
SET configuration_parameter { TO value | = value | FROM CURRENT } | Sets a configuration parameter to the specified value when the procedure is entered, then restores it to its prior value on exit. SET FROM CURRENT saves the current value of the parameter at procedure entry time. A SET LOCAL inside the procedure is restricted to the procedure's scope. An ordinary SET (without LOCAL) overrides this clause; its effect persists after the procedure exits unless the current transaction is rolled back. |
PRAGMA AUTONOMOUS_TRANSACTION | Marks the procedure as an autonomous transaction. |
Volatility attributes
| Attribute | Behavior |
|---|---|
IMMUTABLE | The procedure does not modify the database and always returns the same result for the same arguments. The procedure does not perform database lookups or use values outside its argument list. Calls with all-constant arguments can be replaced immediately with the result. |
STABLE | The procedure does not modify the database and returns the same result for the same arguments within a single table scan. Results can differ across SQL statements. Use this for procedures that depend on database lookups or session variables such as the current time zone. |
VOLATILE (default) | The procedure's result can change within a single table scan. No optimizations are applied. Classify any procedure with side effects as VOLATILE even if its results are predictable, to prevent calls from being eliminated during optimization. |
NULL-handling attributes
| Attribute | Behavior |
|---|---|
CALLED ON NULL INPUT (default) | The procedure is called even when some arguments are NULL. The procedure body is responsible for handling NULL values. |
RETURNS NULL ON NULL INPUT / STRICT | The procedure returns NULL immediately if any argument is NULL, without executing the body. |
Parallel attributes
| Attribute | Behavior |
|---|---|
UNSAFE (default) | The procedure cannot run in parallel mode. Any SQL statement containing this procedure forces a serial execution plan. |
RESTRICTED | The procedure can run in parallel mode, but execution is restricted to the parallel group leader. A relation is excluded from parallel execution if its qualification contains a parallel-restricted procedure. |
SAFE | The procedure can run in parallel mode without restrictions. |
Usage notes
STRICT,LEAKPROOF,PARALLEL,COST,ROWS, andSETare PolarDB for PostgreSQL (Compatible with Oracle) extensions and are not supported by Oracle databases.IMMUTABLE,STABLE,STRICT,LEAKPROOF,COST,ROWS, andPARALLEL { UNSAFE | RESTRICTED | SAFE }are supported only by stored procedures of PolarDB for PostgreSQL (Compatible with Oracle).Stored procedures are created as
SECURITY DEFINERby default. Stored procedures defined in PL/pgSQL are created asSECURITY INVOKER.
Examples
List employees using a cursor
The following stored procedure retrieves and prints all employees from the emp table:
CREATE OR REPLACE PROCEDURE list_emp
IS
v_empno NUMBER(4);
v_ename VARCHAR2(10);
CURSOR emp_cur IS
SELECT empno, ename FROM emp ORDER BY empno;
BEGIN
OPEN emp_cur;
DBMS_OUTPUT.PUT_LINE('EMPNO ENAME');
DBMS_OUTPUT.PUT_LINE('----- -------');
LOOP
FETCH emp_cur INTO v_empno, v_ename;
EXIT WHEN emp_cur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(v_empno || ' ' || v_ename);
END LOOP;
CLOSE emp_cur;
END;Call the procedure:
EXEC list_emp;Output:
EMPNO ENAME
----- -------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLERUse IN OUT and OUT parameters
The following stored procedure returns an employee's number, name, and job. It first searches by employee number; if no match is found, it falls back to searching by name. An anonymous block calls the procedure:
CREATE OR REPLACE PROCEDURE emp_job (
p_empno IN OUT emp.empno%TYPE,
p_ename IN OUT emp.ename%TYPE,
p_job OUT emp.job%TYPE
)
IS
v_empno emp.empno%TYPE;
v_ename emp.ename%TYPE;
v_job emp.job%TYPE;
BEGIN
SELECT ename, job INTO v_ename, v_job FROM emp WHERE empno = p_empno;
p_ename := v_ename;
p_job := v_job;
DBMS_OUTPUT.PUT_LINE('Found employee # ' || p_empno);
EXCEPTION
WHEN NO_DATA_FOUND THEN
BEGIN
SELECT empno, job INTO v_empno, v_job FROM emp
WHERE ename = p_ename;
p_empno := v_empno;
p_job := v_job;
DBMS_OUTPUT.PUT_LINE('Found employee ' || p_ename);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Could not find an employee with ' ||
'number, ' || p_empno || ' nor name, ' || p_ename);
p_empno := NULL;
p_ename := NULL;
p_job := NULL;
END;
END;
DECLARE
v_empno emp.empno%TYPE;
v_ename emp.ename%TYPE;
v_job emp.job%TYPE;
BEGIN
v_empno := 0;
v_ename := 'CLARK';
emp_job(v_empno, v_ename, v_job);
DBMS_OUTPUT.PUT_LINE('Employee No: ' || v_empno);
DBMS_OUTPUT.PUT_LINE('Name : ' || v_ename);
DBMS_OUTPUT.PUT_LINE('Job : ' || v_job);
END;Output:
Found employee CLARK
Employee No: 7782
Name : CLARK
Job : MANAGERUse AUTHID DEFINER and SET clauses
The following stored procedure grants the privileges of the role that defined it to the role calling it. The SET clause scopes the search path and working memory to the procedure:
CREATE OR REPLACE PROCEDURE update_salary(id INT, new_salary NUMBER)
SET SEARCH_PATH = 'public' SET WORK_MEM = '1MB'
AUTHID DEFINER IS
BEGIN
UPDATE emp SET salary = new_salary WHERE emp_id = id;
END;These settings apply only within update_salary and do not affect other stored procedures, functions, or objects.
To use the privileges of the calling role instead, replace AUTHID DEFINER with AUTHID CURRENT_USER.