简体   繁体   中英

How to put result of a query inside a loop in a Cursor in a PL SQL procedure?

I have to use the data from a clob to do a query in a loop and store the result of each query in a cursor. However i am not sure how/where to open a cursor. If i do it in a loop then i assume only the last query's data will be present.

What is the way to go in such a situation.

This is what I am trying to achieve :

https://www.mkyong.com/jdbc/jdbc-callablestatement-stored-procedure-cursor-example/

PROCEDURE PRC(
              P_DATE    IN     VARCHAR,
              P_CLOB    IN     CLOB,
              P_CUR        OUT SYS_REFCURSOR
             ) IS
    V_DATE                                  DATE;
    V_STR                                   VARCHAR;
BEGIN
    V_DATE           := TO_DATE(P_DATE, 'DD/MM/YYYY');
    V_CLOB_LENGTH    := DBMS_LOB.getlength(P_CLOB);
    V_START_CHAR     := 1;
    V_LEN            := 5;

    WHILE (V_START_CHAR + V_LEN) <= V_CLOB_LENGTH
    LOOP
        V_STR           := SUBSTR(
                                  P_CLOB,
                                  V_START_CHAR,
                                  V_LEN
                                 );
        V_START_CHAR    := V_START_CHAR + V_LEN;


    OPEN P_CUR FOR  /* I know this is wrong */
        SELECT A , B, C
        FROM TAB
        WHERE DATE = V_DATE
          AND COL = V_STR; 


    END LOOP;
END PRC;

If I were you, I'd do the chunking up of the clob in a query and then you can simply join that to your table - something like:

PROCEDURE PRC(P_DATE IN VARCHAR,
              P_CLOB IN CLOB,
              P_CUR  OUT SYS_REFCURSOR)
IS
  v_length constant number := 5;
BEGIN
  OPEN p_cur FOR
    SELECT tab.a,
           tab.b,
           tab.c
    FROM   tab
           INNER JOIN (SELECT to_char(p_date, 'dd/mm/yyyy') dt,
                              dbms_lob.SUBSTR(p_clob, v_length, (LEVEL - 1)*v_length + 1) substring
                       FROM   dual
                       CONNECT BY dbms_lob.SUBSTR(p_clob, v_length, (LEVEL - 1)*v_length + 1) IS NOT NULL) str
             ON tab.dt = str.dt
                AND tab.col = str.substring;
END prc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM