Search code examples
oracle-databasefor-loopplsqlcursoralias

Retrieving variables using for loop and aliases in a cursor


I am trying to use a for loop to print a set of data and was curious if it is possible to use an alias to retrieve the information or how I would do this for the for loop

DECLARE
job_ VARCHAR2(35);
employee_name VARCHAR2(35);
manager_name VARCHAR2(35);
salary_difference NUMBER(20,2);
CURSOR cur_salary_difference IS
    SELECT job_title, employees.first_name || ' ' || employees.last_name "Employee", 
    m.first_name || ' ' || m.last_name "Manager", (employees.salary-m.salary) "Salary Difference" 
    FROM employees
    LEFT OUTER JOIN employees m ON
       employees.manager_id = m.employee_id
       JOIN jobs j ON employees.job_id = j.job_id
    ORDER BY "Employee";
BEGIN
    DBMS_OUTPUT.PUT_LINE('Listings of employees with salary difference compared to manager');
    FOR people IN cur_salary_difference LOOP
        DBMS_OUTPUT.PUT_LINE (chr(10) || 'Job Title:' || people.job_title);
        DBMS_OUTPUT.PUT_LINE ('Employee:' || people.employee);
        DBMS_OUTPUT.PUT_LINE ('Manager:' || people.manager);
        DBMS_OUTPUT.PUT_LINE ('Salary Difference:' || salary_difference);

    END LOOP;
END;

Solution

    1. You should try it.
    2. Yes, aliases will work. Since you've put the aliases in double-quotes, Oracle will treat them as case sensitive and you need double quotes later when you use them. (Which is why you shouldn't double quote identifiers, 99% of the time.)