Sub topic 11
Anchoring data types with %TYPE
This chapter assumes you can write an anonymous PL/SQL block with DECLARE, BEGIN, and END. It also assumes you can declare a variable and fill it with SELECT INTO. The examples use the HR.EMPLOYEES table and a small helper table that you create. You need a client that runs PL/SQL, such as SQL*Plus, SQL Developer, or SQLcl.
The problem: hard-coded data types
Suppose you declare a variable to hold a last name:
v_last_name VARCHAR2(25);This works until a DBA widens last_name to VARCHAR2(50). Any row with a longer name now raises ORA-06502: PL/SQL: numeric or value error when your code reads it into the variable. The same problem occurs when you change a NUMBER precision. You then have to find every hard-coded declaration that copies that column's type and edit it by hand.
The %TYPE attribute solves this. It tells PL/SQL: "give this variable the same data type as that column or that variable."
Syntax and the four things you can anchor to
variable_name referenced_item%TYPE [NOT NULL] [:= initial_value];The referenced item can be any of these:
| Referenced item | Example |
|---|---|
| A table or view column | `employees.salary%TYPE` |
| A column qualified by schema | `hr.employees.salary%TYPE` |
| A variable or constant declared earlier | `v_salary%TYPE` |
| A field of a record | `v_emp.salary%TYPE` |
You write no length, precision, or scale. They come from the referenced item.
Anchoring to a column
This block is the standard pattern for reading a row into variables.
SET SERVEROUTPUT ON
DECLARE
v_last_name employees.last_name%TYPE;
v_salary employees.salary%TYPE;
BEGIN
SELECT last_name, salary
INTO v_last_name, v_salary
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE(v_last_name || ' earns ' || v_salary);
END;
/If salary is NUMBER(8,2), then v_salary is NUMBER(8,2). PL/SQL looks this up in the data dictionary when it compiles the block.
Anchoring to another variable
Use a variable as the anchor when a value is derived from another one. The new variable then follows the same type, and so indirectly follows the column.
SET SERVEROUTPUT ON
DECLARE
v_salary employees.salary%TYPE;
v_new_salary v_salary%TYPE;
BEGIN
SELECT salary INTO v_salary
FROM employees
WHERE employee_id = 100;
v_new_salary := v_salary * 1.1;
DBMS_OUTPUT.PUT_LINE('Old: ' || v_salary || ', new: ' || v_new_salary);
END;
/The referenced variable must be declared before the line that uses it. If it is not, you get PLS-00201: identifier must be declared.
What %TYPE does and does not copy
A variable declared with %TYPE inherits some properties of the referenced item and ignores others.
| Property | Inherited? |
|---|---|
| Data type | Yes |
| Length, precision, scale | Yes |
| `NOT NULL` constraint from a table column | No |
| `NOT NULL` from a variable declared `NOT NULL` | Yes |
| Initial value | No |
| `CONSTANT` status | No |
The difference between columns and variables causes the most surprises.
SET SERVEROUTPUT ON
DECLARE
v_last employees.last_name%TYPE; -- the column is NOT NULL, the variable is not
v_limit NUMBER(3) NOT NULL := 10;
v_cap v_limit%TYPE := 20; -- inherits NOT NULL, so it needs a value
BEGIN
IF v_last IS NULL THEN
DBMS_OUTPUT.PUT_LINE('v_last is NULL: the column constraint was not inherited');
END IF;
DBMS_OUTPUT.PUT_LINE('v_cap = ' || v_cap);
END;
/If you remove := 20 from v_cap, compilation fails with PLS-00218: a variable declared NOT NULL must have an initialization assignment. Table constraints such as NOT NULL, CHECK, and foreign keys are enforced by the database when you run DML. They are not enforced on PL/SQL variables.
Seeing the benefit: a schema change
This demonstration uses a helper table, so you can run it in any schema where you can create tables. First create the table and a short name:
CREATE TABLE demo_staff (
staff_id NUMBER(6) PRIMARY KEY,
staff_name VARCHAR2(10) NOT NULL
);
INSERT INTO demo_staff VALUES (1, 'Ada');
COMMIT;Next widen the column and store a longer name. Then run one block with a hard-coded type and one with %TYPE.
SET SERVEROUTPUT ON
ALTER TABLE demo_staff MODIFY (staff_name VARCHAR2(40));
UPDATE demo_staff
SET staff_name = 'Grace Brewster Murray Hopper'
WHERE staff_id = 1;
COMMIT;
DECLARE
v_name VARCHAR2(10);
BEGIN
SELECT staff_name INTO v_name FROM demo_staff WHERE staff_id = 1;
DBMS_OUTPUT.PUT_LINE('Hard-coded: ' || v_name);
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Hard-coded: value too long for the variable');
END;
/
DECLARE
v_name demo_staff.staff_name%TYPE;
BEGIN
SELECT staff_name INTO v_name FROM demo_staff WHERE staff_id = 1;
DBMS_OUTPUT.PUT_LINE('Anchored: ' || v_name);
END;
/The first block prints the error message. The second prints Anchored: Grace Brewster Murray Hopper and needed no edit.
%TYPE in stored subprograms
In a stored procedure or function, %TYPE is also useful for parameters and return types.
CREATE OR REPLACE FUNCTION get_salary (
p_emp_id IN employees.employee_id%TYPE
) RETURN employees.salary%TYPE
IS
v_salary employees.salary%TYPE;
BEGIN
SELECT salary INTO v_salary
FROM employees
WHERE employee_id = p_emp_id;
RETURN v_salary;
END get_salary;
/Parameters never carry a size in their declaration, so %TYPE here only supplies the data type, not a constraint. A stored unit also records a dependency on the table. If you alter a column it references, Oracle can mark the unit INVALID. It recompiles on its next call, and with %TYPE it recompiles against the new definition. You can check the state with this query:
SELECT object_name, status
FROM user_objects
WHERE object_name = 'GET_SALARY';An anonymous block is not stored, so it is compiled again each time you run it.
Naming and the column-name trap
Give variables a prefix such as v_, constants c_, and parameters p_. A variable named exactly like a column causes silent bugs, because SQL inside the block resolves the name to the column first:
DECLARE
salary employees.salary%TYPE := 5000;
BEGIN
DELETE FROM employees WHERE salary = salary; -- compares the column to itself
END;
/Do not run this block. The WHERE clause is true for every row with a non-null salary, so it would delete them all. A prefix such as v_salary removes the ambiguity.
Limits of %TYPE
- It follows structure, not meaning. If a column changes from
NUMBERtoDATE, the variable changes too, and arithmetic in your code may then fail to compile or run. - It does not size expressions. In
SELECT salary * 12 INTO v_salary, the result is stored in a variable sized for a monthly salary. A value too large for the precision raisesORA-06502. Declare a separate variable for derived values when they can be larger. - The target must exist and be visible. A misspelled table gives
PLS-00201. A missing column givesPLS-00302: component must be declared. Lack of privilege on the table also givesPLS-00201. - It does not take a default. Always provide your own initial value where you need one.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `PLS-00201` on a `%TYPE` line | Table or variable not visible, or declared later | Fix the name or grant access. Declare the anchor first. |
| `PLS-00218` | Anchor variable is `NOT NULL`, so the new one needs a value | Add `:= value` |
| `ORA-06502` after `SELECT INTO` | The value is larger than the anchored type | Use a wider variable for derived values |
| Variable is `NULL` when you expected a constraint | Column `NOT NULL` is not inherited | Check for `NULL` in your own code |
Exercise
A table column orders.total is NUMBER(10,2). You write v_total orders.total%TYPE; v_tax v_total%TYPE;. Later the column becomes NUMBER(14,2). What must you change in the PL/SQL code, and what happens if orders.total was declared NOT NULL in the table?
Show answer
Nothing needs to change. Both variables take the new precision when the code is next compiled, because v_tax follows v_total, which follows the column. The table's NOT NULL is not inherited, so both variables can hold NULL.
Exercise
What error does this block raise, and how do you fix it? DECLARE vmax NUMBER(3) NOT NULL := 100; vmin v_max%TYPE; BEGIN NULL; END;
Show answer
It fails to compile with PLS-00218, because v_min inherits NOT NULL from v_max and has no initial value. Fix it by giving v_min a value, for example v_min v_max%TYPE := 0;.