cursor

1. Steps

  A. Declare the cursor

  B, open the cursor

  C. read data

  D. Close the cursor

 

2. Properties

  A. %ISOPEN: Boolean, whether the cursor is open.

  B. %FOUND: Boolean, whether data is read.

  C. %NOTFOUND: The opposite of %FOUND.

  D. %ROWCOUNT: Numerical type, returns the number of rows for which data has been extracted from the cursor buffer so far.

  

3. Cursor application

   A. Browsing data

--loop
set serveroutput on
declare
  uname t_user.name%type;
  cursor myCur is -- define the cursor
   select name from t_user;
begin
  if not myCur%ISOPEN then
    open myCur; -- open the cursor
  end if;
  loop
     fetch myCur into uname; -- read data
     exit when myCur%notfound;
     dbms_output.put_line(uname);
   end loop;
   close myCur; -- close the cursor
   exception -- exception
     when no_data_found then
       dbms_output.put_line('Data does not exist!');
end;
/
--for will automatically open the cursor, when the data is traversed, exit the loop and close the cursor
set serveroutput on
declare
  cursor myCur is -- define the cursor
   select name from t_user;
begin
  for user in myCur loop
     dbms_output.put_line(user.name);
   end loop;
  exception -- exception
     when no_data_found then
       dbms_output.put_line('Data does not exist!');
end;
/

   

   B. Modify the data (modify the data with 'a' in the name)

declare
  uid t_user.id%type;
  cursor myCur is
    select u.id
    from t_user u
    where u.name like '%a%'
    for update; --for update adds a row shared lock on the cursor result set
begin
   if not myCur%ISOPEN then
      open myCur; -- open the cursor
   end if;
   loop
     fetch myCur into uid;
     exit when myCur%notfound;
     case uid
       when 1 then
         update t_user u set u.name = 'Array'
         where current of myCur; --Modify the data currently pointed to by the cursor
       else
         update t_user u set u.name = 'vector'
         where current of myCur;
      end case;
   end loop;
   close myCur;
end;
/

 

   C. to delete data

declare
uid t_user.id%type;
cursor myCur is
  select u.id
  from t_user u
  where u.name like '%a%'
  for update;
begin
 if not myCur%ISOPEN then
   open myCur; -- open the cursor
 end if;
 fetch myCur into uid;--get a record first
 while myCur%found loop
   if uid = 1 then -- condition, if id is 1 delete
     delete from t_user where current of myCur;
   end if;
   fetch myCur into uid;--traverse a record
 end loop;
 close myCur;
end;
/

 

Guess you like

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