Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
37
Добавлен:
16.04.2013
Размер:
5.97 Mб
Скачать

Using Correlated Subqueries

END;

/

Using Correlated Subqueries

While a subquery is evaluated only once for each table, a correlated subquery is evaluated once for each row. The following example returns the name and salary of each employee whose salary exceeds the departmental average. For each row in the table, the correlated subquery computes the average salary for the corresponding epartment.

DECLARE

--For each department, we find the average salary.

--Then we find all the employees in that department making

--more than that average salary.

CURSOR c1 IS

SELECT department_id, last_name, salary FROM employees t

WHERE salary >

(

SELECT AVG(salary) FROM employees

WHERE

t.department_id = department_id

)

ORDER BY department_id; BEGIN

FOR person IN c1 LOOP

dbms_output.put_line('Making above-average salary = ' || person.last_name);

END LOOP; END;

/

Writing Maintainable PL/SQL Queries

Instead of referring to local variables, you can declare a cursor that accepts parameters, and pass values for those parameters when you open the cursor. If the query is usually issued with certain values, you can make those values the defaults. You can use either positional notation or named notation to pass the parameter values.

Example 6–1 Passing Parameters to a Cursor FOR Loop

The following example computes the total wages paid to employees in a specified department.

DECLARE

CURSOR c1 (name VARCHAR2, max_wage NUMBER) IS

SELECT * FROM employees WHERE last_name = name and salary < max_wage; BEGIN

FOR person IN c1('Austin', 30000) LOOP

-- process data record

dbms_output.put_line('Name = ' || person.last_name || ', salary = ' || person.salary);

Performing SQL Operations from PL/SQL 6-15

Соседние файлы в папке Oracle 10g