Sub topic 3
Loading variables with SELECT INTO
This chapter assumes you can write basic SELECT statements, know Oracle types such as NUMBER and VARCHAR2, and can run an anonymous block in SQL*Plus or SQLcl. The examples use the HR sample table EMPLOYEES.
Loading variables with SELECT INTO
SELECT ... INTO runs a query and stores the returned column values in PL/SQL variables. The INTO list must have one variable for each selected column, in the same order.
SET SERVEROUTPUT ON
DECLARE
v_last_name VARCHAR2(25);
v_salary NUMBER(8,2);
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;
/The query must return exactly one row. Zero rows or several rows raise an error, covered at the end of this chapter.
Anchoring data types with %TYPE
Hard-coding a type such as VARCHAR2(25) breaks silently if the column changes later. The %TYPE attribute copies the type of a column or variable, so the declaration follows the schema.
DECLARE
v_last_name employees.last_name%TYPE;
v_salary employees.salary%TYPE;Matching a whole row with %ROWTYPE
%ROWTYPE declares a record with one field for each column of a table. Use it when you need the whole row.
SET SERVEROUTPUT ON
DECLARE
v_emp employees%ROWTYPE;
BEGIN
SELECT * INTO v_emp
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE(v_emp.first_name || ' ' || v_emp.last_name);
END;
/Handling NO_DATA_FOUND and TOO_MANY_ROWS
SELECT INTO raises NO_DATA_FOUND when no row matches and TOO_MANY_ROWS when more than one row matches. Handle both in the EXCEPTION section.
SET SERVEROUTPUT ON
DECLARE
v_last_name employees.last_name%TYPE;
BEGIN
SELECT last_name INTO v_last_name
FROM employees
WHERE employee_id = -1;
DBMS_OUTPUT.PUT_LINE(v_last_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee with that ID.');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('More than one row matched.');
END;
/Exercise
Why does the INTO list need the same number of variables as the selected columns?
Show answer
SELECT INTO assigns values by position. If the counts differ, the statement fails to compile, and mismatched types or order can load the wrong values into variables.