📜  for select oracle - SQL (1)

📅  最后修改于: 2023-12-03 14:41:18.303000             🧑  作者: Mango

For Select Oracle - SQL

For select is a loop statement in Oracle SQL that allows you to loop through a set of rows selected by a query. This is useful when you want to perform some operation on each row in the result set. Let's explore this statement in more detail.

Syntax

The syntax for for select loop is as follows:

FOR record_variable IN (SELECT column1, column2, ... FROM table) LOOP
   -- do something with record_variable
END LOOP;

Here record_variable is the variable used to hold each row of data as the loop iterates through the result set. The SELECT statement in the parentheses selects the columns and rows to be processed by the loop.

Example

Let us consider an example where you want to retrieve the details of employees who earn more than $5000 and increase their salaries by 10% using for select loop.

FOR emp_rec IN (SELECT employee_id, first_name, last_name, salary FROM employees WHERE salary > 5000) LOOP
   -- increase salary by 10%
   emp_rec.salary := emp_rec.salary * 1.1;

   -- update employee table
   UPDATE employees SET salary = emp_rec.salary WHERE employee_id = emp_rec.employee_id;

   -- print new salary information
   DBMS_OUTPUT.PUT_LINE(emp_rec.first_name || ' ' || emp_rec.last_name || ' new salary: ' || emp_rec.salary);
END LOOP;

In this example, we first select all employees who earn more than $5000 using a WHERE clause. We then use for select loop to update the salary of each employee by 10% and print their new salary.

Conclusion

for select statement is a useful feature in Oracle SQL that allows you to loop through a set of rows selected by a query. It can be used to perform various operations on each row in the result set.