Use Oracle Cursor in Proc and Return it?

守給你的承諾、 提交于 2019-12-11 12:49:18

问题


I am working on a package that will return two cursors. One cursor is a list of items with a numeric primary key. The other cursor is a list of files associated with the items

Code so far:

procedure get_items_with_files(
           o_results out sys_refcursor,
           o_files out sys_refcursor
) is 
begin

   begin
      open o_results for
          select item_id,
                 item_name
          from items;
   end;

   begin
      open o_files for
           select item_id
                  item_file_name
           from item_files if
           where if.item_id in (select item_id from TABLE(CAST(o_results)));
   end;
end get_items_with_files;

The areas I am running into problems with:

  1. Getting a missing keyword error on the table(cast(cursor)) section
  2. Can I access the cursor in the code as I am or do i need to copy it to an internal variable? I tried to create a variable of sys_refcursor type and a "set v_cursor := o_results" but got a missing or invalid option error.

回答1:


You can't use the O_RESULTS cursor to open the O_FILES cursor.

You can query the ITEMS table in order to open both cursors but that introduces the possibility that some data changes between when you open the O_RESULTS cursor and the time you open the O_FILES cursor and that the two result sets are out of sync.

procedure get_items_with_files(
           o_results out sys_refcursor,
           o_files out sys_refcursor
) is 
begin

   begin
      open o_results for
          select item_id,
                 item_name
          from items;
   end;

   begin
      open o_files for
           select item_id
                  item_file_name
           from item_files if
           where if.item_id in (select item_id from items);
   end;
end get_items_with_files;

It would be much more common to return a single cursor that represents the result of joining the two tables

procedure get_items_with_files(
           o_results out sys_refcursor
) is 
begin
  open o_results for
      select item_id,
             item_name,
             item_file_name
        from items
             join item_files using (item_id);
end get_items_with_files;

If all your procedure is doing is opening a cursor, however, it would be more common to create a view rather than creating a procedure and then query the view rather than calling the procedure.



来源:https://stackoverflow.com/questions/9523552/use-oracle-cursor-in-proc-and-return-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!