plsql中游标使用

打开游标后的循环  

declare

  i_total integer:=1000;
  cursor emp_cur is select * from emp order by salary asc;
  i_emp emp%rowtype;
  begin
    open emp_cur;
    loop
      fetch emp_cur into i_emp;
      exit when emp_cur%notfound;
      i_total:=i_total+i_emp.salary;
      end loop;
     close emp_cur;
      dbms_output.put_line(i_total);
      end;

      select into 

create or replace procedure t_p(emp_id number) is
 v_name varchar2(1000);
begin
  select first_name into v_name from emp where employee_id=emp_id;
  dbms_output.put_line(v_name);
  end;
  


      动态查询

create or replace procedure p1(employee_id number, department_id number) is
      i_name varchar2(100);
      begin
        execute immediate 'select first_name from emp where employee_id='||employee_id ||' and department_id='||department_id into i_name;
        dbms_output.put_line(i_name);
        end;


动态查询,结果放到集合中

create or replace procedure p2(department_id number) is
  type names is table of varchar2(100);
  i_name names;
begin
  execute immediate 'select first_name from emp where department_id=' ||
                    department_id bulk collect
    into i_name;
  for idx in 1 .. i_name.count loop
    dbms_output.put_line(i_name(idx));
  end loop;
end;


游标变量

游标变量的使用范围

  • Pass a cursor variable back to the host environment that called the program unit—the result set can be “consumed” for display or other processing.

  • Construct a result set inside a function, and return a cursor variable to that set. This is especially handy when you need to use PL/SQL, in addition to SQL, to build the result set.

  • Pass a cursor variable to a pipelined table function—a powerful but quite advanced optimization technique. A full explanation of cursor variables, including the differences between strong and weak REF CURSOR types, is beyond the scope of this article.

  • Instead, I will show the basic syntax for working with cursor variables and identify situations in which you might consider using this feature


  CREATE OR REPLACE FUNCTION names_for(name_type_in IN VARCHAR2)
    RETURN SYS_REFCURSOR IS
    l_return SYS_REFCURSOR;
  BEGIN
    CASE name_type_in
      WHEN 'EMP' THEN
        OPEN l_return FOR
          SELECT last_name FROM emp ORDER BY employee_id;
      WHEN 'DEPT' THEN
        OPEN l_return FOR
          SELECT name FROM departments ORDER BY id;
    END CASE;
  
    RETURN l_return;
  END names_for;



使用游标变量
DECLARE
   l_names   SYS_REFCURSOR;
   l_name    VARCHAR2 (32767);
BEGIN
   l_names := names_for ('DEPT');


   LOOP
      FETCH l_names INTO l_name;


      EXIT WHEN l_names%NOTFOUND;
      DBMS_OUTPUT.put_line (l_name);
   END LOOP;


   CLOSE l_names;
END;
 


你可能感兴趣的:(plsql中游标使用)