Recursive Pipelined function in PL/SQL

I've always thought pipelined functions were awesome, even more awesome though is a recursive pipelined function. For me, each function iteration calls a web service that returns xml describing a list of files and folders in a given directory. I then call the function on each folder.

The awesomeness:
Piping piped rows.

To use this you will need to replace <TABLE_SOURCE> with the function you use to get your table. For me, I make a web service call and throw the result into an XMLtable, and select from that.
 FUNCTION LIST_PIPE
(
    LIST_URL VARCHAR2
    ,RECURSIVE VARCHAR DEFAULT 'false'
) RETURN LIST_TABLE_TYPE
    PIPELINED IS
    
BEGIN
    
    FOR I IN (SELECT A.ITEM AS ITEM
       ,A.IS_FOLDER AS IS_FOLDER
      FROM <TABLE_SOURCE> A )
    LOOP
       PIPE ROW(LIST_ROW_TYPE(I.ITEM, I.IS_FOLDER));
       IF RECURSIVE = 'true' AND I.IS_FOLDER = 'true'
       THEN
          FOR J IN (SELECT * FROM TABLE(LIST_PIPE(I.ITEM, RECURSIVE)))
          LOOP
             PIPE ROW(LIST_ROW_TYPE(J.ITEM, J.IS_FOLDER));
          END LOOP;
       END IF;
    END LOOP;

END LIST_PIPE;

You will need the following two global types.
CREATE OR REPLACE TYPE LIST_ROW_TYPE AS OBJECT
(
              ITEM          VARCHAR2(4000),
              IS_FOLDER     VARCHAR2(10)
)
..and..
create or replace type LIST_TABLE_TYPE as TABLE OF LIST_ROW_TYPE

1 comment:

  1. I feel this is a very crucial and deeper analysis of a problem which exists in the process of SQL.Thanks to the respective blogger for putting up this.

    SQL Server Load Rest Api


    ReplyDelete