游标分类:1、显式 explicit2、隐式 implicit游标属性:1、%FOUND 有数据可取(bool)2、%ISOPEN 是否打开3、%NOTFOUND 没有数据可取(bool)4、%ROWCOUNT 已经取得游标的数量一、DEFINITION OF CURSORDECLARE
CURSOR mycur IS
SELECT * FROM books; --DECLARE CURSOR
myrecord books%ROWTYPE; --DECLARE A RECORD ,AND THE RECORD PROPERTY IS FROM THE TABLE BOOKS
BEGIN
OPEN mycur; --OPEN CURSOR
FETCH mycur INTO myrecord;--FETCH ONE Record TO RECORD FROM CURSOR
WHILE mycur%FOUND LOOP -- LOOP WHEN HAS RECORDS
DBMS_OUTPUT.PUL_LINE(myrecord.books_id ',' myrecord.books_name);
FETCH mycur INTO myrecord;--FETCH ONE Record TO RECORD FROM CURSOR AGAIN
END LOOP; --END LOOP
CLOSE mycur;--CLOSE CURSOR
END;
/
二、CURSOR WITH PARAMETER
DECLARE
CURSOR cur_para(id varchar2) IS --The parameter just need a type
SELECT books_name FROM books WHERE books_id=id;
t_name books.books_name%TYPE;
BEGIN
OPEN cur_para('0001');
LOOP
FETCH cur_para INTO t_name;
EXIT WHEN cur_para%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(t_name);
END LOOP;
CLOSE cur_para;
END;
/
三、DECLARE CURSOR WITH PARAMETER USE FOR..LOOP
DECLARE
CURSOR cur_para(id varchar2) IS
SELECT books_name FROM books WHERE books_id=id;
BEGIN
DBMS_OUTPUT.PUT_LINE('*********************');
FOR cur IN cur_para('0001') LOOP --FOR LOOP, NO NEED TO DECLARE THE cur.
DBMS_OUTPUT.PUT_LINE(cur.books_name);
END LOOP;
END;
/
四、DECLARE CURSOR WITH PARAMETER (%ISOPEN)
DECLARE
t_name books.books_name%TYPE;
CURSOR cur(id varchar2) IS
SELECT books_name FROM books WHERE books_id=id;
BEGIN
IF cur%ISOPEN THEN --%ISOPEN
DBMS_OUTPUT.PUT_LINE('CURSOR HAS BEEN OPENED!');
ELSE
OPEN CUR('0003');
END IF;
FETCH cur INTO t_name;
CLOSE cur;
DBMS_OUTPUT.PUT_LINE(t_name);
END;
/
五、DECLARE CURSOR (%ROWCOUNT)
DECLARE
t_name varchar2(10);
CURSOR mycur IS
SELECT books_name FROM books;
BEGIN
OPEN mycur;
LOOP
FETCH mycur INTO t_name;
EXIT WHEN mycur%NOTFOUND OR mycur%NOTFOUND IS NULL;
DBMS_OUTPUT.PUT_LINE('游标mycur的ROWCOUNT是:' mycur%ROWCOUNT);--GET THE CURRENT ROW NUMBER
END LOOP;
CLOSE mycur;
END;
/
五、DECLARE CURSOR FOR UPDATE
DECLARE
CURSOR cur IS
SELECT books_name FROM books FOR UPDATE;--DECLARE FOR UPDATE
text varchar2(10);
BEGIN
OPEN cur;
FETCH cur INTO text;
WHILE cur%FOUND LOOP
UPDATE books SET books_name=books_name '_t' WHERE CURRENT OF cur;
FETCH cur INTO text;
END LOOP;
CLOSE cur;
END;
/
六、DECLARE CURSOR --implicit
--This is a way of implicit CURSOR,and the FOR..LOOP no need to declare cur.Like POINT THREE.
BEGIN
FOR cur IN(SELECT books_name FROM books) LOOP
DBMS_OUTPUT.PUT_LINE(cur.books_name);
END LOOP;
END;
/
--转自