【oracle-学习篇】-游标cursors

本文目录:

一、什么是游标?

游标:当一个SQL语句执行时,在系统内存中临时创建的工作区域。游标包含select语句的查询信息和数据存取的行数。
 
这个临时工作区域用于存储从数据库检索出来的数据,并且操纵这个区域。一个游标可以保存多行数据,但是在同一时间只能操纵一行数据。被游标持有的行集合称为活动集。
在PL/SQL里定义了两种类型的游标:隐式游标和显示游标。

二、隐式游标

These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. 

Implicit Cursors: Application

When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit statements are created to process these statements.

Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN. 

For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected. 
When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no data is selected.

The status of the cursor for each of these attributes are defined in the below table. 

Attributes

Return Value

Example

%FOUND

The return value is TRUE, if the DML statements like INSERT, DELETE and UPDATE affect at least one row and if SELECT ….INTO statement return at least one row.

SQL%FOUND

The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE do not affect row and if SELECT….INTO statement do not return a row.

%NOTFOUND

The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE at least one row and if SELECT ….INTO statement return at least one row.

SQL%NOTFOUND

The return value is TRUE, if a DML statement like INSERT, DELETE and UPDATE do not affect even one row and if SELECT ….INTO statement does not return a row.

%ROWCOUNT

Return the number of rows affected by the DML operations INSERT, DELETE, UPDATE, SELECT

SQL%ROWCOUNT

 

For Example: Consider the PL/SQL Block that uses implicit cursor attributes as shown below:

 1 DECLARE  var_rows number(5);
 2 BEGIN
 3   UPDATE employee 
 4   SET salary = salary + 1000;
 5   IF SQL%NOTFOUND THEN
 6     dbms_output.put_line('None of the salaries where updated');
 7   ELSIF SQL%FOUND THEN
 8     var_rows := SQL%ROWCOUNT;
 9     dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');
10   END IF; 
11 END; 

In the above PL/SQL Block, the salaries of all the employees in the ‘employee’ table are updated. If none of the employee’s salary are updated we get a message 'None of the salaries where updated'. Else we get a message like for example, 'Salaries for 1000 employees are updated' if there are 1000 rows in ‘employee’ table. 

 

 
 
posted @ 2013-10-28 18:08  vs人民币  阅读(207)  评论(0)    收藏  举报