Introduction of Oracle PL/SQL cursor

a definition

A cursor, also called a cursor, is a Result Set.
 
two grammar
CURSOR cursor name [(parameter name data type [, parameter name data type]...)]
IS SELECT statement;
 
Three cursor usage
1. Define the cursor
cursor c1 is select ename from emp;
2. Open the cursor to execute the query
open c1;
3. Take a line to a variable
fetch c1 into pename;


 
4. Close close to release resources
close c1;
 
Four examples
1. Demand
Use the cursor to query the employee's name and salary, and print it.
2. Code
  1. --查询并打印员工的姓名和薪水
  2. /*
  3. 1.光标属性
  4. %found %notfound
  5. */
  6. set serveroutput on
  7. declare
  8. --定义一个光标
  9. cursor cemp isselect ename,sal from emp;
  10. --为光标定义对应的变量
  11. pename emp.ename%type;
  12. psal emp.sal%type;
  13. begin
  14. --打开光标
  15. open cemp;
  16. loop
  17. --取一条记录
  18. fetch cemp into pename,psal;
  19. --思考:1循环什么时候退出?2fetch不一定能取到记录
  20. --exitwhen没有取到记录
  21. exitwhen cemp%notfound;
  22. dbms_output.put_line(pename||'的薪水是'||psal);
  23. end loop;
  24. --关闭光标
  25. close cemp;
  26. end;
  27. /
3. Running results
SMITH's salary is 800
ALLEN's salary is 1600
WARD salary is 1250
JONES' salary is 2975
MARTIN's salary is 1250
BLAKE's salary is 2850
CLARK's salary is 2450
SCOTT's salary is 3000
King's salary is 5000
TURNER's salary is 1500
ADAMS salary is 1100
JAMES' salary is 950
FORD's salary is 3000
MILLER's salary is 1300
 
PL/SQL procedure completed successfully.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326187546&siteId=291194637