Using default values in parameters v16

You can set a default value of a formal parameter by including the DEFAULT clause or using the assignment operator (:=) in the CREATE PROCEDURE or CREATE FUNCTION statement.

Syntax

The general form of a formal parameter declaration is:

(<name> [ IN|OUT|IN OUT ] <data_type> [{DEFAULT | := } <expr> ])

name is an identifier assigned to the parameter.

IN|OUT|IN OUT specifies the parameter mode.

data_type is the data type assigned to the variable.

expr is the default value assigned to the parameter. If you don't include a DEFAULT clause, the caller must provide a value for the parameter.

The default value is evaluated every time you invoke the function or procedure. For example, assigning SYSDATE to a parameter of type DATE causes the parameter to have the time of the current invocation, not the time when the procedure or function was created.

Example

This example uses the assignment operator to set a default value of SYSDATE into the parameter hiredate:

CREATE OR REPLACE PROCEDURE hire_emp (
    p_empno         NUMBER,
    p_ename         VARCHAR2,
    p_hiredate      DATE := SYSDATE
)
IS
BEGIN
    INSERT INTO emp(empno, ename, hiredate)
                   VALUES(p_empno, p_ename, p_hiredate);

    DBMS_OUTPUT.PUT_LINE('Hired!');
END hire_emp;

If the parameter declaration includes a default value, you can omit the parameter from the actual parameter list when you call the procedure. Calls to the sample procedure (hire_emp) must include two arguments: the employee number (p_empno) and employee name (p_empno). The third parameter (p_hiredate) defaults to the value of SYSDATE:

hire_emp (7575, Clark)

If you do include a value for the actual parameter when you call the procedure, that value takes precedence over the default value. This command adds an employee with a hiredate of February 15, 2010, regardless of the current value of SYSDATE.

hire_emp (7575, Clark, 15-FEB-2010)

You can write the same procedure by substituting the DEFAULT keyword for the assignment operator:

CREATE OR REPLACE PROCEDURE hire_emp (
    p_empno         NUMBER,
    p_ename         VARCHAR2,
    p_hiredate      DATE DEFAULT SYSDATE
)
IS
BEGIN
    INSERT INTO emp(empno, ename, hiredate)
                   VALUES(p_empno, p_ename, p_hiredate);

    DBMS_OUTPUT.PUT_LINE('Hired!');
END hire_emp;