WITH clause in CURSOR

Hi,
I was going through some docs on using WITH clause in curosr...but coulcn't understand.
I was going through existing code for customization, that has 'WITH' clause.
I'm trying to understand below piece of code.
could you let me know what the below code is about..
  CURSOR CUR_CRK
  IS
  WITH PTLPM_WITH AS
    (SELECT
      /*+ INDEX(P_TR_LOAN_PAST_MONTHLY PK_P_TR_LOAN_PAST_MONTHLY) */
    FROM INF.P_TR_LOAN_PAST_MONTHLY
    WHERE POST_DATE    =P_POST_DATE
    AND TREND_GROUP_ID = 'M'
    AND APPL_ID       IN ('FL','LN')
  UIGL_INF_WITH AS
  (SELECT * FROM INF.U_IM_GALL_LOAN
  XHCC_INF_WITH as
  (SELECT * FROM DWC.XREF_HIER_COST_CENTER_11SEP12 --INF.XREF_HIER_COST_CENTER
  )Thanks.

Perhaps a simple example will make it clear...
SQL> ed
Wrote file afiedt.buf
  1  select e.empno, e.ename, d.dname
  2  from        (select * from emp) e
  3         join (select * from dept) d
  4*        on   (e.deptno = d.deptno)
SQL> /
     EMPNO ENAME      DNAME
      7369 SMITH      RESEARCH
      7499 ALLEN      SALES
      7521 WARD       SALES
      7566 JONES      RESEARCH
      7654 MARTIN     SALES
      7698 BLAKE      SALES
      7782 CLARK      ACCOUNTING
      7788 SCOTT      RESEARCH
      7839 KING       ACCOUNTING
      7844 TURNER     SALES
      7876 ADAMS      RESEARCH
      7900 JAMES      SALES
      7902 FORD       RESEARCH
      7934 MILLER     ACCOUNTING
14 rows selected.Ok, a bit of a nonsense query in itself, but it's demonstrating that we have two subqueries that we are getting our data from.
Now, writing the same query using a WITH clause...
SQL> ed
Wrote file afiedt.buf
  1  with e as (select * from emp)
  2      ,d as (select * from dept)
  3  select e.empno, e.ename, d.dname
  4* from   e join d on (e.deptno = d.deptno)
SQL> /
     EMPNO ENAME      DNAME
      7369 SMITH      RESEARCH
      7499 ALLEN      SALES
      7521 WARD       SALES
      7566 JONES      RESEARCH
      7654 MARTIN     SALES
      7698 BLAKE      SALES
      7782 CLARK      ACCOUNTING
      7788 SCOTT      RESEARCH
      7839 KING       ACCOUNTING
      7844 TURNER     SALES
      7876 ADAMS      RESEARCH
      7900 JAMES      SALES
      7902 FORD       RESEARCH
      7934 MILLER     ACCOUNTING
14 rows selected.As you can see, the subqueries have been moved out of the main query and put into the WITH clause, and then the main query just references those subqueries aliases.
In the above example, there's not much point in doing this, but in more complex queries, you may have a subquery that is used several times, in which case having it in the WITH clause means that that subquery is processed just once and used many times, (you can also look at the MATERIALIZE hint to help improve performance with such subqueries if necessary)
The difficulty with finding this in the documentation is because you will no doubt be trying to search for "WITH", which isn't a very good search term to be using as it's used in the english language too much for an accurate hit... so... when you learn it's called "Subquery Factoring" (because you are factoring out the subqueries from the main query), it then becomes easier to find...
http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10002.htm#i2161315
... and you see it's included as part of the documentation for the SQL SELECT statement.

Similar Messages

  • With clause usage in cursor

    is it possible to use with clause in cursor declaration.
    see the below simple example.
    it gives error.
    declare
    cursor t is
    (with hi as
    (select * from pepole )
    select distinct hi.id from hi where id =55);
    begin
    null;
    end;

    Remove the outer set of parenthesis.
    declare
    cursor t is
    with hi as
    (select * from emp )
    select distinct sal from hi;
    begin
    null;
    end;

  • ORA-32031: illegal reference of a query name in WITH clause

    Oracle tutorial : http://www.oracle.com/technology/pub/articles/hartley-recursive.html#4
    When Executing this Query 6: Using a Recursive WITH Clause
    WITH C (CNO, PCNO, CNAME) AS
    (SELECT CNO, PCNO, CNAME -- initialization subquery
    FROM COURSEX
    WHERE CNO = 'C22' -- seed
    UNION ALL
    SELECT X.CNO, X.PCNO, X.CNAME -- recursive subquery
    FROM C, COURSEX X
    WHERE C.PCNO = X.CNO)
    SELECT CNO, PCNO, CNAME
    FROM C;
    Error: ORA-32031: illegal reference of a query name in WITH clause
    kindly suggest what need to do in case of recursion using subquery

    SCOTT@orcl> ed
    Wrote file afiedt.buf
      1  with c as
      2  (
      3  select empno,ename from emp
      4  where deptno=20
      5  union all
      6  select c.empno,c.ename from emp c
      7  where c.deptno=30
      8  )
      9* select * from c
    SCOTT@orcl> /
         EMPNO ENAME
          7566 xx
          7788 xx
          7876 xx
          7902 xx
          7499 xx
          7521 xx
          7654 xx
          7698 xx
          7844 xx
          7900 xx
    10 rows selected.
    SCOTT@orcl> ed
    Wrote file afiedt.buf
      1  with emp as
      2  (
      3  select empno,ename from emp
      4  where deptno=20
      5  union all
      6  select c.empno,c.ename from emp c
      7  where c.deptno=30
      8  )
      9* select * from emp
    SCOTT@orcl> /
    select empno,ename from emp
    ERROR at line 3:
    ORA-32031: illegal reference of a query name in WITH clause
    SCOTT@orcl>You can not use the same table name alongwith WITH clause's cursor name. See as above if i says with C as... its works; but if i says with emp as... it returned ora-32031, because it is the name of table.
    HTH
    Girish Sharma

  • With clause within the cursor ???

    Hello gurus,
    Can we have a with clause within the cursor ???
    something like this ..
    cursor test_cur is
    WITH unpivoted_data     AS
         SELECT DISTINCT
    f.cust_id
              f.office_cd
              f.type_cd
         FROM      refoff      ro,
              cutomer     p,
              office     f
         WHERE     f.cust_id     = p.cust_id
         AND     f.office_cd      = ro.office_cd
         AND      f.type_cd      IN ('ACCT', 'pay')
    SELECT     cust_id
    ,     MAX (CASE WHEN type_cd = 'ACCT' THEN office_id END)     AS acct_office_id
    ,     MAX (CASE WHEN type_cd = 'pay' THEN office_id END)     AS pay_office_id
    FROM     unpivoted_data
    GROUP BY cust_id
    test_cur_rec test_cur% rowtype;
    Begin
    for test_cur_rec in test_cur
    loop
    insert into test1 (.....) values (.......);
    end loop;
    end;
    One more quick question .... How do u guys past in the posting ??? Like somesought of a box .....I have seen lot senior gurus when they are replying, they post the code in some sought of a box ....that makes very easy to understand and take look at the code in the posting....???
    Thank you so much!!!

    Hi,
    user642297 wrote:
    Hello gurus,
    Can we have a with clause within the cursor ???Sure, but don't take my word for it. Try it and see!
    If you get an error, post the error message.
    If you get unexpected results, explain.
    Whenever you have a problem, post your full Oracle version number.
    One more quick question .... How do u guys past in the posting ??? Like somesought of a box .....I have seen lot senior gurus when they are replying, they post the code in some sought of a box ....that makes very easy to understand and take look at the code in the posting....??? Type these 6 characters:
    (all small letters, inside curly brackets) before and after formatted sections.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Ref cursors - 'with' clause

    I am working with a procedure which is returning a ref-cursor to a Java Call. Inside the procedure I see a statment like
    Open t_results for
    with rfq_companies AS
    select statement1),
    rfq_hierarchies AS
    select statement2),
    rfq_relnhierarchies AS
    select statement 3);
    Can anybody explain such an usage for opening a ref cursor ('WITH' clause)?. What is the effect of using this and how Java will interpret this?

    The procedure is still returning a REF CURSOR, regardless of the way the SELECT statements is created. There is no effect as far as Java is concerned.
    Read more on the WITH clause:
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#sthref9697
    in the section: Subquery Factoring

  • OPEN CURSOR using a WITH clause in the select query

    Hi,
    I am using Oracle 9i. I have a requirement where I have a REFCURSOR as an OUT parameter for my procedure. I have declared the TYPE and created the procedure.
    In the procedure, I am using OPEN <cursor_name> FOR <query>;
    Ideally this works in most of the cases that I have tried earlier. However, in the current case I am using a WITH clause in my query to get the results.
    I need help in understanding if the above mentioned syntax would not allow me to use the WITH clause in the query.

    What error do you get , seems to work ok for me on 10g
    SQL> begin
      2  open :cv for 'with x as (select * from emp)  select * from x';
      3  end;
      4  /
    PL/SQL procedure successfully completed.
    SQL> print :cv
         EMPNO
    ENAME
    JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7521
    WARD
    SALESMAN        7698 22-FEB-81       1250        500         30
          7566
    JONES
    MANAGER         7839 02-APR-81       2975                    20
         EMPNO

  • Use of WITH clause

    Hi,
    I am using Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 .
    I am working in a procedure where I want to manipulate the data produced by a WITH AS clause.  But it is giving "PL/SQL: ORA-00942: table or view does not exist" error. A small example to illustrate my problem is given below. Here in the example am just trying to get a replaced string by using the out put of a WITH AS clause.
    SET SERVEROUTPUT ON;
    DECLARE
    CNT INTEGER;
    LETTER CHAR(1);
    REPLACED_STRING VARCHAR2(10);
    BEGIN
    REPLACED_STRING := 'ABC';
    WITH T AS
      (SELECT 'ABC' VAL FROM DUAL),
      TMP (LEN, SUBVAL) AS
      (SELECT LENGTH(VAL) LEN,
        SUBSTR(VAL, 1, INSTR(VAL, 'B', 1, 1)) SUBVAL
       FROM T
       UNION ALL
       SELECT LENGTH(VAL)-1 LEN,
       SUBSTR(VAL, 2, INSTR(VAL, 'C', 1, 1)) SUBVAL
       FROM T
      SELECT COUNT(*) INTO CNT FROM TMP,T ;
      FOR I IN 1..CNT LOOP
      SELECT SUBSTR(SUBVAL,1,1) INTO LETTER FROM  TMP,T;
      SELECT REPLACE(REPLACED_STRING,LETTER,'X')INTO REPLACED_STRING FROM DUAL;
      DBMS_OUTPUT.PUT_LINE(REPLACED_STRING);
    END LOOP;
    END;
    I thought of declaring a cursor which will hold the data produced by WITH clause but it did not work. Can you please let me know what are the possible options to do this.
    Thanks

    I think, I can not use the WITH inside loop as, I want to manipulate on data resulted by WITH reading row by row from it. I have a complex procedure and I wont be able to explain that scenario here and thus i came up with a similar problem through a very simple example. I will try to explain my problem thru my example here.
    The WITH in my example give an out put as :
    SUBVAL
    AB
    BC
      WITH T AS
      (SELECT 'ABC' VAL FROM DUAL),
      TMP (LEN, SUBVAL) AS
      (SELECT LENGTH(VAL) LEN,
        SUBSTR(VAL, 1, INSTR(VAL, 'B', 1, 1)) SUBVAL
       FROM T
       UNION ALL
       SELECT LENGTH(VAL)-1 LEN,
       SUBSTR(VAL, 2, INSTR(VAL, 'C', 1, 1)) SUBVAL
       FROM T
      SELECT subval FROM TMP,T;
    and then by using this in the PLSQL block mentioned above
      FOR I IN 1..CNT LOOP
      SELECT SUBSTR(SUBVAL,1,1) INTO LETTER FROM  TMP,T;
      SELECT REPLACE(REPLACED_STRING,LETTER,'X')INTO REPLACED_STRING FROM DUAL;
      DBMS_OUTPUT.PUT_LINE(REPLACED_STRING);
      END LOOP;
    I want to have an output like:
    XBC
    XXC
    Please note that nature of my original problem is that I want to manipulate the data given by WITH clause in the same procedure by passing it to other functions/procs to get the desired result. So please advice me following this approach only which would be helpful.
    Thanks

  • Using WITH clause in Pro*Cobol

    Hi!
    I am trying to improve the performance of a query by introducing WITH clause.
    The query is in Pro*Cobol Release 9.2.0.6.0 - Production.
    I got compilation error
    WITH DPTCOST AS (
    ...............1
    PCB-S-00400, Encountered the symbol "DPTCOST" when expecting one of the following:
    END-EXEC
    ....continued
    So I wonder if we could use that clause at all with Pro*Cobol
    Here is the excerp of the code
    EXEC SQL
    DECLARE INPUT_ACTUAL CURSOR FOR
    WITH DPTCOST AS (
    SELECT /*+ rule */
    A.CODE_COMBINATION_ID,
    A.SEGMENT1, A.SEGMENT2, A.SEGMENT3,
    A.SEGMENT6,
    D.COSTING, D.PROCESS,
    D.MTL_CODE, D.FACTOR
    FROM
    GL_CODE_COMBINATION A,
    ALCGL_DEPARTMENT_COSTINGS D
    WHERE
    A.TEMPLATE_ID IS NULL
    AND A.SUMMARY_FLAG <> 'Y'
    AND A.SEGMENT1 = D.PLANT_NUMBER
    AND A.SEGMENT3 <> '6999001'
    AND A.SEGMENT3 <> '6999002'
    AND SUBSTR(A.SEGMENT2,4,3) = D.DEPARTMENT
    AND D.ACTUAL_FLAG = 'A'
    ) ... continued

    Materialized views are basically stored query results. They offer advanced functionality like query rewrite, refresh on commit, and more;
    http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_6002.htm
    Unlike a view, they actually store the results of the query - not just the query;
    SQL> create table t (cid number primary key)
    Table created.
    SQL> insert into t select object_id from dba_objects where object_id is not null
    12791 rows created.
    SQL> create materialized view mv
       as select * from t
    Snapshot created.
    SQL> select object_name, object_type from user_objects where object_name ='MV'
    OBJECT_NAME                    OBJECT_TYPE       
    MV                             TABLE             
    MV                             MATERIALIZED VIEW 
    2 rows selected.
    SQL> select segment_name, bytes from user_segments where segment_name in ('T', 'MV')
    SEGMENT_NAME                        BYTES
    T                                  196608
    MV                                 196608
    2 rows selected.Temporary tables are simply tables that are created then dropped. GLOBAL TEMPORARY TABLES have the advantage (or disadvantage) of only existing until commit or the end of the session. They results are visible to the user that inserted the data - but only temporarily;
    http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_7002.htm#sthref7483

  • Passing where and group by clause to cursor

    I am working on a procedure that builds a where clause and needs a group by clause to return the correct results. I am trying to pass both the where and group by variables into the cursor.
    The variables are getting populated correctly, but when the cursor gets created, the variables are not in the cursor.
    Here is the code I'm working with. It is a part of a package, but makes no calls to other parts of the package.
    PROCEDURE createFollowUpTask_Exposure( psUppgkedjetyp IN tis.tial.uppgkedjetyp%TYPE default NULL,
    psAlarmtyp IN tis.tial.alarmtyp%TYPE default NULL,
    psSubtyp IN tis.tial.subtyp%TYPE default NULL,
    pnDays IN NUMBER default NULL,
    psKampkod IN tis.tiin.kampkod%TYPE default NULL,
    psKatnr IN tis.tiin.katnr%TYPE default NULL,
    psUtgava IN tis.tiin.utgava%TYPE default NULL,
    psKatslag IN tis.tikg.katslag%TYPE default NULL,
    psProdsyst IN tis.tikg.prodsyst%TYPE default NULL,
    psUppgtyp IN tis.tiin.uppgtyp%TYPE default NULL,
    psProdkod IN tis.tiin.prodkod%TYPE default NULL,
    psStatus IN tis.tiin.status%TYPE default NULL
    ) AS
    cTIAL tis.tial%ROWTYPE;
    vLopnr tis.tial.lopnr%TYPE;
    vSqlWhere VARCHAR2(4000);
    vGroupBy VARCHAR2(1000) := ' tiin.kampkod, tiin.abnr, tiko.fordsalj';
    cSelectCursor SYS_REFCURSOR;
    vSqlSelect VARCHAR2(4000);
    psDays VARCHAR2(50);
    cRec T_TIAL_REC;
    nCount number := 0;
    CURSOR cSqlSelect( SqlWhere IN VARCHAR2, GroupBy IN VARCHAR2) IS
    SELECT tiin.kampkod, tiin.abnr, tiko.fordsalj, MAX(tici.regdat) ALARMDATE
    FROM tis.tiin
    JOIN tis.tiko ON tiin.kampkod = tiko.kampkod AND tiin.abnr = tiko.abnr
    JOIN core.tici ON tiin.kampkod = tici.kampkod AND tiin.abnr = tici.abnr AND tici.inplnr = tiin.inplnr
    WHERE 1=1 || SqlWhere
    GROUP BY GroupBy;
    BEGIN
    -- If these parameters are null, raise error
    IF psUppgkedjetyp IS NULL and psSubtyp IS NULL THEN
    raise_application_error(-20001,
    'Either Event Chain or Starting Event must be assigned');
    END IF;
    -- Populate TIAL values
    IF psUppgkedjetyp IS NOT NULL THEN
    cTIAL.Uppgkedjetyp := psUppgkedjetyp;
    END IF;
    IF psAlarmtyp IS NOT NULL THEN
    cTIAL.Alarmtyp := psAlarmtyp;
    END IF;
    cTIAL.Handklass := 'T';
    cTIAL.Blobid := 0;
    IF pnDays IS NOT NULL THEN
    psDays := '+ '||pnDays;
    END IF;
    IF psSubtyp IS NOT NULL THEN
    cTIAL.Subtyp := psSubtyp;
    END IF;
    -- Create Where clause for cursor
    vSqlWhere := '';
    IF psKampkod IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.kampkod = '''|| psKampkod||'''';
    END IF;
    IF psKatnr IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.katnr = '''||psKatnr||'''';
    END IF;
    IF psUtgava IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.utgava = '''||psUtgava||'''' ;
    END IF;
    IF psKatslag IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tikg.katslag = '''||psKatslag||'''';
    END IF;
    IF psProdsyst IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tikg.prodsyst = '''||psProdsyst||'''';
    END IF;
    IF psUppgtyp IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.uppgtyp = '''||psUppgtyp||'''';
    END IF;
    IF psProdkod IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.prodkod = '''||psProdkod||'''';
    END IF;
    IF psStatus IS NOT NULL THEN
    vSqlWhere := vSqlWhere||' AND tiin.status = '''||psStatus||'''';
    END IF;
    -- Loop through all records meeting input parameters and set required TIAL values.
    FOR i IN cSqlSelect(vSqlWhere, vGroupBy)
    LOOP
    --FETCH cSelectCursor INTO cRec;             
    cTIAL.Kampkod := '';
    cTIAL.Abnr := '';
    cTIAL.Sign := '';
    cTIAL.Alarmdate := '';
    cTIAL.Kampkod := i.Kampkod;
    cTIAL.Abnr := i.Abnr;
    cTIAL.Sign := i.fordsalj;
    cTIAL.Alarmdate := i.alarmdate;
    nCount := nCount + 1;
    IF vLopnr = -1 THEN
    raise_application_error(-20002,
    'Error Creating task for: '||cTIAL.Kampkod||' '||cTIAL.Abnr||' Sales Rep: '||cTIAL.Alarmdate);
    END IF;
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('I created '||nCount||' records.');
    END createFollowUpTask_Exposure;
    Thanks in advance for any help.

    Hi,
    Welcome to the forum!
    Try this (not tested) as an example:
    PROCEDURE createFollowUpTask_Exposure(psUppgkedjetyp IN tis.tial.uppgkedjetyp%TYPE DEFAULT NULL,
                                          psAlarmtyp     IN tis.tial.alarmtyp%TYPE DEFAULT NULL,
                                          psSubtyp       IN tis.tial.subtyp%TYPE DEFAULT NULL,
                                          pnDays         IN NUMBER DEFAULT NULL,
                                          psKampkod      IN tis.tiin.kampkod%TYPE DEFAULT NULL,
                                          psKatnr        IN tis.tiin.katnr%TYPE DEFAULT NULL,
                                          psUtgava       IN tis.tiin.utgava%TYPE DEFAULT NULL,
                                          psKatslag      IN tis.tikg.katslag%TYPE DEFAULT NULL,
                                          psProdsyst     IN tis.tikg.prodsyst%TYPE DEFAULT NULL,
                                          psUppgtyp      IN tis.tiin.uppgtyp%TYPE DEFAULT NULL,
                                          psProdkod      IN tis.tiin.prodkod%TYPE DEFAULT NULL,
                                          psStatus       IN tis.tiin.status%TYPE DEFAULT NULL) AS
       cTIAL         tis.tial%ROWTYPE;
       vLopnr        tis.tial.lopnr%TYPE;
       vSqlWhere     VARCHAR2(4000);
       vGroupBy      VARCHAR2(1000) := ' tiin.kampkod, tiin.abnr, tiko.fordsalj';
       cSelectCursor SYS_REFCURSOR;
       vSqlSelect    VARCHAR2(4000);
       psDays        VARCHAR2(50);
       cRec          T_TIAL_REC;
       nCount        NUMBER := 0;
       FUNCTION fnc_cSqlSelect(SqlWhere IN VARCHAR2,
                               GroupBy  IN VARCHAR2) RETURN VARCHAR2 IS
       BEGIN
          RETURN 'SELECT tiin.kampkod,
                 tiin.abnr,
                 tiko.fordsalj,
                 MAX(tici.regdat) ALARMDATE
            FROM tis.tiin
            JOIN tis.tiko ON tiin.kampkod = tiko.kampkod
                         AND tiin.abnr = tiko.abnr
            JOIN core.tici ON tiin.kampkod = tici.kampkod
                          AND tiin.abnr = tici.abnr
                          AND tici.inplnr = tiin.inplnr
           WHERE 1 = 1 ' || SqlWhere || ' GROUP BY ' || GroupBy;
       END fnc_cSqlSelect;
    BEGIN
       -- If these parameters are null, raise error
       IF psUppgkedjetyp IS NULL AND psSubtyp IS NULL THEN
          raise_application_error(-20001,
                                  'Either Event Chain or Starting Event must be assigned');
       END IF;
       -- Populate TIAL values
       IF psUppgkedjetyp IS NOT NULL THEN
          cTIAL.Uppgkedjetyp := psUppgkedjetyp;
       END IF;
       IF psAlarmtyp IS NOT NULL THEN
          cTIAL.Alarmtyp := psAlarmtyp;
       END IF;
       cTIAL.Handklass := 'T';
       cTIAL.Blobid    := 0;
       IF pnDays IS NOT NULL THEN
          psDays := '+ ' || pnDays;
       END IF;
       IF psSubtyp IS NOT NULL THEN
          cTIAL.Subtyp := psSubtyp;
       END IF;
       -- Create Where clause for cursor
       vSqlWhere := '';
       IF psKampkod IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.kampkod = ''' || psKampkod || '''';
       END IF;
       IF psKatnr IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.katnr = ''' || psKatnr || '''';
       END IF;
       IF psUtgava IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.utgava = ''' || psUtgava || '''';
       END IF;
       IF psKatslag IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tikg.katslag = ''' || psKatslag || '''';
       END IF;
       IF psProdsyst IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tikg.prodsyst = ''' || psProdsyst || '''';
       END IF;
       IF psUppgtyp IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.uppgtyp = ''' || psUppgtyp || '''';
       END IF;
       IF psProdkod IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.prodkod = ''' || psProdkod || '''';
       END IF;
       IF psStatus IS NOT NULL THEN
          vSqlWhere := vSqlWhere || ' AND tiin.status = ''' || psStatus || '''';
       END IF;ç
       -- Loop through all records meeting input parameters and set required TIAL values.
       OPEN cSelectCursor FOR fnc_cSqlSelect(vSqlWhere,
                                             vGroupBy);
       LOOP
          FETCH cSelectCursor
             INTO v; -- You must define a variable 'v' to hold the data of cursor
          EXIT WHEN cSelectCursor%NOTFOUND;
          --FETCH cSelectCursor INTO cRec;
          cTIAL.Kampkod   := '';
          cTIAL.Abnr      := '';
          cTIAL.Sign      := '';
          cTIAL.Alarmdate := '';
          cTIAL.Kampkod   := i.Kampkod;
          cTIAL.Abnr      := i.Abnr;
          cTIAL.Sign      := i.fordsalj;
          cTIAL.Alarmdate := i.alarmdate;
          nCount := nCount + 1;
          IF vLopnr = -1 THEN
             raise_application_error(-20002,
                                     'Error Creating task for: ' || cTIAL.Kampkod || ' ' ||
                                     cTIAL.Abnr || ' Sales Rep: ' || cTIAL.Alarmdate);
          END IF;
       END LOOP;
       CLOSE cSelectCursor;
       DBMS_OUTPUT.PUT_LINE('I created ' || nCount || ' records.');
    END createFollowUpTask_Exposure;
    /Regards,

  • WITH clause

    Hi All,
    I am new to PL/SQL.
    I have a query where I am using WITH clause. And,it is to be used in a cursor.
    so my doubt is ,where should I need to place the WITH clause ? In Declare section or BEGIN section.
    Please suggest.
    We tried both ways but couldn't end up with a solution.I have also searched in the forums.
    Can anyone post a sample query.
    Thank you.
    Regards,
    Santhosh.

    Hi All,
    Thanks for ur reply.
    The psuedo code am using is given below.
    I am using 2 cursors(CUR1OFF_1,CUR1_1) for 2 WITH clause(TEMP_Q1,TEMP_Q2) respectively.
    And 2 more cursors (CUR1OFF,CUR1) for using the above (TEMP_Q1,TEMP_Q2) directly.
    Its erroring out.
    Can anyone please helpme out on this.
    DECLARE
    cursor CUR1OFF_1
    is
    with TEMP_Q1
    AS
    (SELECT * FROM TAB1,TAB2
    WHERE TAB1.EMPID=TAB2.EMPID)
    SELECT * FROM TEMP_Q1;
    cursor CUR_1
    is
    with TEMP_Q2
    AS
    (SELECT * FROM TAB3,TAB4
    WHERE TAB3.EMPID=TAB4.EMPID)
    SELECT * FROM TEMP_Q2;
    cursor CUR1OFF
    is
    SELECT * FROM TEMP_Q1
    UNION
    SELECT * FROM TEMP_Q2
    cursor CUR
    is
    SELECT * FROM TEMP_Q1 WHERE EMPNAME='X'
    UNION
    SELECT * FROM TEMP_Q2 WHERE EMPNAME='X'
    BEGIN
    END;
    Thank You,
    Santhosh

  • WITH clause in PL/SQL

    Hi All,
    Can WITH clause be used in PL/SQL, example, as in during creating a cursor or inserting into a table by selecting data from another table?
    I received the following error while compiling a procedure which makes use of WITH.
    105/6    PLS-00103: Encountered the symbol "WITH" when expecting one of
             the following:
             ( select
    and line 105 has only WITHDatabase : 10.2.0.2.0
    Thanks,
    ...

    Hi Flake,
    As far as I remember, you could not do this in 9i, dunno about 10.2.0.2
    SQL> create table t (x number)
    Table created.
    SQL> declare
    begin
       insert into t(x)
          with t2 as (select 2 x from dual)
          select x
            from t2;
       commit;
    end;
    PL/SQL procedure successfully completed.
    SQL> select * from t
             X
             2
    1 row selected.
    SQL> select * from v$version where rownum = 1
    BANNER                                                         
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    1 row selectedRegards
    Peter

  • Construct a Sql block using With Clause to improve the performance

    I have got four diff parametrized cursor in my Pl/Sql Procedure. As the performance of the Procedure is very pathetic,so i have been asked to tune the Select statements used in those cursors.
    So I am trying to use the With Clause in order to club all those four Select Statements.
    I would appreciate if anybody can help me to construct the Sql Block using With Clause.
    My DB version is..
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    PL/SQL Release 11.1.0.7.0 - Production
    Four Diff cursors are defined below.
    CURSOR all_iss (
          b_batch_end_date   IN   TIMESTAMP,
       IS
          SELECT isb.*
                FROM IMPLMN_STEP_BREKPN  isb
               , ISSUE iss
          WHERE isb.issue_id = iss.issue_id
           AND iss.issue_status_id  =  50738
           AND ewo_no IN
          (SELECT TO_CHAR(wo_no)
            FROM MGO_PLANT_AUDIT
           WHERE dml_status = 'U' OR dml_status = 'I')
          UNION ALL
          SELECT isb.*
           FROM IMPLMN_STEP_BREKPN  isb
            , ISSUE iss
           WHERE isb.issue_id = iss.issue_id
           AND iss.issue_status_id  =  50738
           AND CAST (isb.last_updt_timstm AS TIMESTAMP) >=
                                                                  b_batch_end_date;
          CURSOR ewo_plant  ( p_ewo_no IN  IMPLMN_STEP_BREKPN.ewo_no%TYPE)
          IS
          SELECT DISTINCT wo_no ,
          plant_code
          FROM MGO_PLANT
          WHERE TO_CHAR(wo_no) = p_ewo_no;
          CURSOR iss_ewo_plnt (
          p_issue_id IN IMPLMN_STEP_BREKPN.issue_id%TYPE ,
          p_ewo_no IN IMPLMN_STEP_BREKPN.EWO_NO%TYPE,
          p_plnt_code IN IMPLMN_STEP_BREKPN.PLT_FACLTY_ID%TYPE)
          IS
          SELECT *
          FROM IMPLMN_STEP_BREKPN
          WHERE issue_id = p_issue_id
          AND ewo_no = p_ewo_no
          AND
          (plt_faclty_id = p_plnt_code
          OR
          plt_faclty_id IS NULL);
          CURSOR iss_ewo_plnt_count (
          p_issue_id IN IMPLMN_STEP_BREKPN.issue_id%TYPE ,
          p_ewo_no IN IMPLMN_STEP_BREKPN.EWO_NO%TYPE,
          p_plnt_code IN IMPLMN_STEP_BREKPN.PLT_FACLTY_ID%TYPE)
          IS
          SELECT COUNT(*)
          FROM IMPLMN_STEP_BREKPN
          WHERE issue_id = p_issue_id
          AND ewo_no = p_ewo_no
          AND
          (plt_faclty_id = p_plnt_code
          OR
          plt_faclty_id IS NULL);

    Not tested. Some thing like below. i just made the queries as tables and given name as a,b,c and substituted columns for the parameters used in the 2nd cursor and third cursor. Try like this.
    CURSOR all_iss (
    b_batch_end_date IN TIMESTAMP,
    IS
    select a.*,b.*,c.* from
    ( SELECT isb.*
    FROM IMPLMN_STEP_BREKPN isb
    , ISSUE iss
    WHERE isb.issue_id = iss.issue_id
    AND iss.issue_status_id = 50738
    AND ewo_no IN
    (SELECT TO_CHAR(wo_no)
    FROM MGO_PLANT_AUDIT
    WHERE dml_status = 'U' OR dml_status = 'I')
    UNION ALL
    SELECT isb.*
    FROM IMPLMN_STEP_BREKPN isb
    , ISSUE iss
    WHERE isb.issue_id = iss.issue_id
    AND iss.issue_status_id = 50738
    AND CAST (isb.last_updt_timstm AS TIMESTAMP) >=
    b_batch_end_date) a,
    ( SELECT DISTINCT wo_no ,
    plant_code
    FROM MGO_PLANT
    WHERE TO_CHAR(wo_no) = p_ewo_no) b,
    ( SELECT *
    FROM IMPLMN_STEP_BREKPN
    WHERE issue_id = p_issue_id
    AND ewo_no = p_ewo_no
    plt_faclty_id IS NULL) c
    where b.wo_no = c.ewo_no and
    c.issue_id = a.issue_id ;
    vinodh
    Edited by: Vinodh2 on Jul 11, 2010 12:03 PM

  • Syntax help needed in update using 'WITH' Clause

    Update     CP_JP_CORP_FSASA_FEEDUPLOAD_r r
                             set     (
                                   gfrn,                              
                                   tenor_code,
                                   tenor_description,
                                   exposure_category,          
                                   frr,          
                                   facility_classification,
                                   limit_amount,
                                   limit_usd,
                                   approval_ccy,
                                   approval_date,
                                   expiry_date,
                                   avail_status_code,
                                   avail_status_desc,
                                   revolving_indicator,
                                   committed_flag,
                                   committed_until_date,
                                   committed_amount,
                                   advised_flag,
                                   advised_amount,
                                   facility_long_description,
                                   booking_unit_code,
                                   extending_unit_code,
                                   extending_unit_short_desc,
                                   approving_unit_code,
                                   approving_unit_short_des,
                                   transaction_type,
                                   branch_no
                                   =
                                            With t as
                                                 Select     fac.gfrn,fac.tenor_code,fac.tenor_description,fac.exposure_category,fac.frr,
                                                      fac.facility_classification,fac.limit_amount,fac.limit_usd,fac.approval_ccy,
                                                      fac.approval_date,fac.expiry_date,fac.avail_status_code,fac.avail_status_desc,
                                                      fac.revolving_indicator,fac.committed_flag,fac.committed_until_date,fac.committed_amount,
                                                      fac.advised_flag,fac.advised_amount,fac.facility_long_description,fac.booking_unit_code,
                                                      fac.extending_unit_code,fac.extending_unit_short_desc,fac.approving_unit_code,fac.approving_unit_short_des,
                                                      /*'Check' normalflag,
                                                      cust.adjusted_orr fsasaorr1stborrower,
                                                      'Normal' category1stborrower,
                                                      cust.adjusted_orr fsasaorr2ndborrower,
                                                      'Normal' category2ndborrower,
                                                      cust.adjusted_orr fsasaorrfinal,
                                                      'Normal' categoryfinal */
                                                      txn.transaction_type,txn.branch_no,txn.gfcid,txn.transaction_id
                                                 from     cp_fsa_boj_corp_cr_fac_hist fac,
                                                           --cp_fsa_boj_corp_cr_cust_hist cust,
                                                           cp_fsa_boj_corp_cr_txn_hist txn
                                                 where     fac.gfcid = txn.gfcid
                                                           and fac.facility_id = txn.facility_id
                                                           and fac.as_of_date = txn.as_of_date
                                                           and to_char(fac.as_of_date,'yyyymm') = p_financial_period
                                                           and fac.as_of_date = last_day(fac.as_of_date)
                                            select      t.gfrn,
                                                      t.tenor_code,
                                                      t.tenor_description,
                                                      t.exposure_category,
                                                      t.frr,
                                                      t.facility_classification,
                                                      t.limit_amount,
                                                      t.limit_usd,                                             
                                                      t.approval_ccy,                                             
                                                      t.approval_date,                                             
                                                      t.expiry_date,                                             
                                                      t.avail_status_code,                                             
                                                      t.avail_status_desc,                                             
                                                      t.revolving_indicator,                                             
                                                      t.committed_flag,                                             
                                                      t.committed_until_date,                                             
                                                      t.committed_amount,                                             
                                                      t.advised_flag,                                             
                                                      t.advised_amount,                                             
                                                      t.facility_long_description                                             
                                                      t.booking_unit_code,                                             
                                                      t.extending_unit_code,                                             
                                                      t.extending_unit_short_desc,                                        
                                                      t.approving_unit_code,                                             
                                                      t.approving_unit_short_des,                                             
                                                      t.transaction_type,
                                                      t.branch_no
                                            from     t
                                       where      r.financialperiod           = p_financial_period
                                                 and exists
                                                           Select     1
                                                           from     t
                                                           where     t.transaction_id = r.ce_trans_id
                                                      )I'm facing syntax problem

    Hii All,
    This is my actual update.(I stopped performing dml operations in cursors following Karthick Arp) :-)
    Update     CP_JP_CORP_FSASA_FEEDUPLOAD_r r
                             set     (
                                   gfrn,                              
                                   tenor_code,
                                   tenor_description,
                                   exposure_category,          
                                   frr,          
                                   facility_classification,
                                   limit_amount,
                                   limit_usd,
                                   approval_ccy,
                                   approval_date,
                                   expiry_date,
                                   avail_status_code,
                                   avail_status_desc,
                                   revolving_indicator,
                                   committed_flag,
                                   committed_until_date,
                                   committed_amount,
                                   advised_flag,
                                   advised_amount,
                                   facility_long_description,
                                   booking_unit_code,
                                   extending_unit_code,
                                   extending_unit_short_desc,
                                   approving_unit_code,
                                   approving_unit_short_des,
                                   transaction_type,
                                   branch_no
                                   = (          
                                       Select     fac.gfrn,fac.tenor_code,fac.tenor_description,fac.exposure_category,fac.frr,
                                            fac.facility_classification,fac.limit_amount,fac.limit_usd,fac.approval_ccy,
                                            fac.approval_date,fac.expiry_date,fac.avail_status_code,fac.avail_status_desc,
                                            fac.revolving_indicator,fac.committed_flag,fac.committed_until_date,fac.committed_amount,
                                            fac.advised_flag,fac.advised_amount,fac.facility_long_description,fac.booking_unit_code,
                                            fac.extending_unit_code,fac.extending_unit_short_desc,fac.approving_unit_code,fac.approving_unit_short_des,
                                            txn.transaction_type,txn.branch_no
                                       from     cp_fsa_boj_corp_cr_fac_hist fac,
                                                 --cp_fsa_boj_corp_cr_cust_hist cust,
                                                 cp_fsa_boj_corp_cr_txn_hist txn
                                       where     fac.gfcid = txn.gfcid
                                                 and fac.facility_id = txn.facility_id
                                                 and fac.as_of_date = txn.as_of_date
                                                 and to_char(fac.as_of_date,'yyyymm') = p_financial_period
                                                 and fac.as_of_date = last_day(fac.as_of_date)
                             where Exists
                                                 Select     1
                                                 from     cp_fsa_boj_corp_cr_fac_hist fac,
                                                           cp_fsa_boj_corp_cr_txn_hist txn
                                                 where     fac.gfcid = txn.gfcid
                                                           and fac.facility_id = txn.facility_id
                                                           and fac.as_of_date = txn.as_of_date
                                                           and to_char(fac.as_of_date,'yyyymm') = p_financial_period
                                                           and fac.as_of_date = last_day(fac.as_of_date)
                                                           and txn.transaction_id = r.ce_trans_id
                                            )Now in my update I'm using same 'SELECT' twice once in 'SET' and again in 'EXISTS' clause. I'd like to make use of 'WITH' Clause and avoid unnecessary 'SELECT' . Please help me.

  • WITH clause unexpectedly causes ORA-00942 in Reports Builder

    I'm posting this in the hope that:
    a) My workaround might help someone if they ever run into the same problem, and/or,
    b) Someone might have a better workaround.
    The problem is that I get unexpected ORA-00942 (table or view does not exist) errors when I try to set the SQL Query Statement property of a Query object in Reports Builder to certain SELECT statements that contain a WITH clause (aka subquery factoring clause).
    For example, the following SELECT statement executes as expected in SQL*Plus...
    SQL> WITH
      2      SUB_QUERY AS
      3      (
      4          SELECT
      5              1 AS X
      6          FROM
      7              DUAL
      8      )
      9  SELECT
    10      INLINE_VIEW.X
    11  FROM   
    12      (
    13          SELECT
    14              NESTED_INLINE_VIEW.X
    15          FROM
    16              (
    17                  SELECT
    18                      SUB_QUERY.X
    19                  FROM
    20                      SUB_QUERY
    21              ) NESTED_INLINE_VIEW
    22      ) INLINE_VIEW;
             X
             1...but when I try to use it as the SQL Query Statement for a Query object in Reports Builder, I get the following error:
    ORA-00942: table or view does not exist
    ==>SUB_QUERY
    My Reports Builder version is 10.1.2.0.2 version and my database version is 10.2.0.3.0.
    The "real" query I have been trying to use is much more complex than this -- this is just the simplest statement I have been able to come up with that causes the problem. In fact, I have some queries that have a similar structure (a WITH clause subquery referenced inside a nested inline view, along with some other things), but strangely do not cause the problem.
    I spent some time researching the problem on Google and Metalink but did not come up with any satisfactory answers. The problem sounds similar to bug 3896963, but bug 3896963 involved UNION ALL, and is supposedly fixed in my version(s).
    I tried various ways of restructuring my "real" query, but with no success -- it's going to be hard to get rid of the WITH clauses. As a "wild guess", I tried various hints (MATERIALIZE, NO_PUSH_PRED, NO_MERGE), again with no success.
    I ended up working around the problem by creating a database package with a function that returns a REF CURSOR based on the query, and then used that in a REF CURSOR query in Reports Builder. It might not be a very elegant workaround, but it works. I just wish I had "given up" and tried it sooner -- I might have saved myself some grief.

    Well, for what it's worth, I didn't end up using a REF CURSOR query after all because...
    If I ran a REP file based on a REF CURSOR query against a different database, or if I ran the REP file after the database package had been dropped and re-created, it failed with the following error:
    REP-8: Run time error in the PL/SQL development environment (DE).
    PDE-PSD001 Could not resolve reference to <Unknown Program Unit> while loading <Unknown> <Unknown>.
    REP-0008: Unexpected memory error while initializing preferences.
    It seems that Reports "binds" the REP file to the timestamp of the database package that defines the REF CURSOR type in order to validate the package at run time. If the timestamp is different, running the REP file will fail with this error. This is apparently bug 1275333 and is described in Metalink Note 272936.1.
    The bug reference and Metalink Note offerred the following workarounds:
    1. Export the database schema that contains the package from one database and import it into the other.
    In some versions, import and export preserve the timestamp, so this would avoid the problem. I didn't try this because it would not be a practical workaround in my situation (upgrade vs. new install).
    2. Recompile the package and manually set the timestamp using the seemingly undocumented ALTER PACKAGE...COMPILE BODY REUSE SETTINGS TIMESTAMP... syntax.
    I didn't try this because I didn't like the idea of having to: a) rely on an undocumented feature, and, b) manually keep track and maintain the timestamps of all the affected packages across several databases (e.g., development, test, and production).
    3. Put the package into a Reports library or into the report itself.
    This didn't work for me because Reports does not understand WITH clauses in PL/SQL. For example, with the example query in my previous post, I get an error like this:
    Error 103 at line {line defining name of factored subquery}, column {first column in line defining name of factored subquery}
    Encountered the symbol "SUB_QUERY" when expecting one of the following:
    &lt;a SQL statement&gt;
    4. Use an RDF file instead of a REP file.
    I didn't use this workaround because I wanted to protect the design of the report by using a REP file instead of an RDF file.
    So instead, I:
    1. Created a database package containing a pipelined function that returned the results of the WITH clause query that Reports did not "understand".
    2. Used an SQL query in my report of the form
    SELECT * FROM TABLE(MY_PACKAGE.MY_PIPELINED_FUNCTION(arg1, arg2, ...))
    I can drop and re-create the package and run the REP file against another database both without leading to the REP-8 error.

  • Regarding with clause

    Hi can any say whether we can use with caluse in cursors.

    any select query having dynamic views in from clause can be used as with, and can be used in cursor tooo
    example of with
    http://nimishgarg.blogspot.com/2010/05/oracle-sql-with-clause-subquery.html

Maybe you are looking for

  • PSE 9 only works with old AIR version on Win 7 x64. Adobe please help.

    I'm hoping that Adobe can jump in and help here as there are some real versioning issues with the components that PSE 9 uses.  I've made a number of posts in the Adobe AIR forum (while I was figuring this out) and have exchanged with Adobe resources

  • Personal web site not showing up.

    Problem: neither web sites appear when using 192.168.2.149 ip addresses. blah, blah . . . so, after setting the Personal Web Sharing tab, the bottom tells me that I can access the computer web site via http://192.168.149 and my personal web page via

  • Audigy 4 digital out to kenwood HTB-6

    i am wondering how i can get digital out to work to my theater system, i tried what said in manual the exact cord but it don't detect the signal. (http://rsk.imageg.net/graphics/uc/rsk/Support/ProductManuals/30504_PM_EN.pdf)Message Edited by Arbiter

  • Video between Mac & PC

    Hey everyone, I don't know if it is possible but can a mac user use the isight to send video to a PC with MSN? Which applications is needed to make it happen?

  • File icons shrunk - HELP!

    For some reason, all of my file icons have shrunk. I have gone into Finder's view preferences and my icon size hasn't changed. It is set to 44x44. For some reasons the file icons are around 20x20. Is there a way to change this back? Message was edite