Nested loops and if statements

I have four schemas with a problem category table "gppcat" that
has problem categories and problem descriptions. I need to
output these categories and descriptions to a csv file. while
doing this I need to make sure I don't include duplicate
records. I use schema 1 as a system of record. I want to select
pcode "category" from schema 1 and loop through to compare each
record in the other schemas and write each unique record once to
the file. I have included the code I am writing. I son't have
much experience in PL/SQL, I usually write in ABAP or Java so
the looping and if logic may seem incongruent as I have never
implemented this in PL/SQL before. Thanks in advance, all the
answers I have gotten fomr this forum have been great.
CURSOR C1
IS
SELECT PCODE, PDESC FROM gpcomp1.gppcat;
CURSOR C2
IS
SELECT PCODE, PDESC FROM gpcomp2.gppcat;
CURSOR C3
IS
SELECT PCODE, PDESC FROM gpcomp3.gppcat;
CURSOR C4
IS
SELECT PCODE, PDESC FROM gpcomp4.gppcat;
-- error handling routine. we will handle all file access errors
-- and data access errors in this procedure err_processing
PROCEDURE err_processing (p_errFileHandle UTL_FILE.FILE_TYPE,
p_lineNum PLS_INTEGER,
p_errText VARCHAR2)
IS
BEGIN
lv_errorFile := UTL_FILE.FOPEN(p_errDir,p_errFile,'W');
UTL_FILE.PUT_LINE( lv_errorFile, lv_initErrorLog );
UTL_FILE.FFLUSH(lv_errorFile);
UTL_FILE.FCLOSE(lv_errorFile);
UTL_FILE.FCLOSE_ALL;
END err_processing;
-- Retreive data into cursors
BEGIN
catFileHandle := UTL_FILE.FOPEN(p_dirName,p_fileName,'W');
Here we need to loop through 4 companies and write all Problem
Codes (pcode) and
Problem Descriptions (pdesc) without writing duplicates. In this
case we are using
the same logic in the old extract by using the US company as the
driving table.
We compare the pcode, record by record in eanch 4 companies.
When we find a unique
record we write it to the file.
FOR catLine1 IN C1
LOOP
     FOR catLine2 IN C2
     LOOP
     IF catLine2.pcode = catLine1.pcode THEN
     writeLine:= (catLine1.pcode) || ',' ||
(catLine1.pdesc);
          UTL_FILE.PUT_LINE( catFileHandle, writeLine );
     ELSE
     writeLine:= (catLine2.pcode) || ',' ||
(catLine2.pdesc);
          UTL_FILE.PUT_LINE( catFileHandle, writeLine );
     END IF;
     END LOOP;
     FOR catLine3 IN C3
     LOOP
     IF catline3.pcode = catLine1.pcode THEN
     writeLine:= (catLine1.pcode) || ',' ||
(catLine1.pdesc);
          UTL_FILE.PUT_LINE( catFileHandle, writeLine );
     ELSE
     writeLine:= (catLine3.pcode) || ',' ||
(catLine3.pdesc);
          UTL_FILE.PUT_LINE( catFileHandle, writeLine );
     END IF;
     END LOOP;
     FOR catLine4 IN C4
     LOOP
     IF catline4.pcode = catLine1.pcode THEN
     writeLine:= (catLine1.pcode) || ',' ||
(catLine1.pdesc);
          UTL_FILE.PUT_LINE( catFileHandle, writeLine );
     ELSE
     writeLine:= (catLine4.pcode) || ',' ||
(catLine4.pdesc);
          UTL_FILE.PUT_LINE( catFileHandle, writeLine );
     END IF;
     END LOOP;
     EXIT WHEN C1%NOTFOUND;
     UTL_FILE.PUT_LINE( catFileHandle, writeLine );
END LOOP;
UTL_FILE.FFLUSH(catFileHandle);
UTL_FILE.FCLOSE(catFileHandle);
Thanks again.
-Pat

The easiest way of doing this is to use the UNION operator.
You just have one cursor, viz:
CURSOR C1
IS
SELECT PCODE, PDESC FROM gpcomp1.gppcat
UNION
SELECT PCODE, PDESC FROM gpcomp2.gppcat
UNION
SELECT PCODE, PDESC FROM gpcomp3.gppcat
UNION
SELECT PCODE, PDESC FROM gpcomp4.gppcat;
This will return only unique rows (to get duplicates you use
UNION ALL). Then you can use a single CURSOR LOOP structure to
write out the result set:
FOR lrec IN C! loop
utl_file.put_line(C1.pcode);
END LOOP;
HTH, APC

Similar Messages

  • Building Tree hierarchy Using nested loops and class cl_gui_column_tree

    Hello gurus,
    I want to create a tree report using custom container and class cl_gui_column_tree. I have read and understood the standard demo report which SAP has provided i.e. SAPCOLUMN_TREE_CONTROL_DEMO. But in this report all the levels nodes are created as constants and hardcoded. I want to create hierarchy using nested loops. For this i took one example of a hierarchy of VBAK-VBELN->VBAP-POSNR Like One sales order has many line items and each line item can have number of line items in billing plan.
    I have done some coding for it.
    FORM build_tree USING node_table TYPE treev_ntab
                                           item_table TYPE zitem_table.              " i created the zitem_table table type of mtreeitm in SE11.
      DATA: node TYPE treev_node,
                 item TYPE mtreeitm.
      node-node_key = root.
      CLEAR node-relatkey.
      CLEAR node-relatship.
      node-hidden = ' '.
      node-disabled = ' '.
      CLEAR node-n_image.
      CLEAR node-exp_image.
      node-isfolder = 'X'.
      node-expander = 'X'.
      APPEND node TO node_table.
      item-node_key = root.
      item-item_name = colm1.
      item-class = cl_gui_column_tree=>item_class_text.
      item-text = 'Root'.
      APPEND item TO item_table.
      item-node_key = root.
      item-item_name = colm2.
      item-class = cl_gui_column_tree=>item_class_text.
      item-text = 'Amount'.
      APPEND item TO item_table.
      LOOP AT it_vbeln INTO wa_vbeln.
        node-node_key = wa_vbeln-vbeln.
        node-relatkey = root.
        node-relatship = cl_gui_column_tree=>relat_last_child.
        node-hidden = ' '.
        node-disabled = ' '.
        CLEAR node-n_image.
        CLEAR node-exp_image.
        node-isfolder = 'X'.
        node-expander = 'X'.
        APPEND node TO node_table.
        item-node_key = wa_vbeln-vbeln.
        item-item_name = colm1.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_vbeln-vbeln.
        APPEND item TO item_table.
        item-node_key = wa_vbeln-vbeln.
        item-item_name = colm2.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_vbeln-netwr.
        APPEND item TO item_table.
        LOOP AT it_posnr INTO wa_posnr.
        node-node_key = wa_posnr-posnr.
        node-relatkey = wa_vbeln-vbeln.
        node-relatship = cl_gui_column_tree=>relat_last_child.
        node-hidden = ' '.
        node-disabled = ' '.
        CLEAR node-n_image.
        CLEAR node-exp_image.
        node-isfolder = ' '.
        node-expander = ' '.
        APPEND node TO node_table.
        item-node_key = wa_posnr-posnr.
        item-item_name = colm1.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_posnr-posnr.
        APPEND item TO item_table.
        item-node_key = wa_posnr-posnr.
        item-item_name = colm2.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_posnr-netpr.
        APPEND item TO item_table.
        ENDLOOP.
      ENDLOOP.
    ENDFORM.
    Now this program compiles fine and runs till there is only one level. That is root->vbeln. But when i add one more loop of it_posnr it gives me runtime error of message type 'X'. The problem i found was uniqueness of item-item_name as all the sales order have posnr = 0010. What could be done? I tried giving item_name unique hierarchy level using counters just like stufe field in prps eg. 10.10.10, 10.10.20,10.20.10,10.20.20,20.10.10 etc.. etc.. but still i am getting runtime error when i add one more hierarchy using nested loop. Plz guide.
    Edited by: Yayati6260 on Jul 14, 2011 7:25 AM

    Hello all,
    Thanks the issue is solved. The node key was not getting a unique identification as nodekey. I resolved the issue by generating unique identification for each level. Thanks all,
    Regards
    Yayati Ekbote

  • Nested Loop and Driving Table.

    In the documentation I read these (/B19306_01/server.102/b14211/optimops.htm#i82080).
    The optimizer uses nested loop joins when joining small number of rows, with a good driving condition between the two tables. You drive from the outer loop to the inner loop, so the order of tables in the execution plan is important.
    The outer loop is the driving row source. It produces a set of rows for driving the join condition. The row source can be a table accessed using an index scan or a full table scan. Also, the rows can be produced from any other operation. For example, the output from a nested loop join can be used as a row source for another nested loop join.>
    I need some help to understand the bold line, i.e. so the order of tables in the execution plan is important.
    There are various conflicting opinion about the driving table (some says smaller and some says larger table is good option) and unfortunately I did not understand any of those logic.
    I read these threads/blogs also.
    CBO (optimizer) nest-loop join question
    http://hoopercharles.wordpress.com/2011/03/21/nested-loops-join-the-smaller-table-is-the-driving-table-the-larger-table-is-the-driving-table/
    In practice, I have seen explain plan for select e.ename,d.dname
      2  from emp e, dept d
      3  where e.deptno=d.deptno; usages emp as driving table (I only understood part of Aman's logic that dept table access would be faster when there would be an index available over it and hence it is in the inner loop)
    Whereas, SQL> explain plan for
      2  select e.ename,d.dname
      3  from emp e, dept d
      4  where e.deptno=d.deptno
      5  and e.deptno=20; usages dept as driving table.
    I have use USE_NL_WITH_INDEX with LEADING hint to change it, but it is giving some adverse effect (sometimes with optimizer_mode ALL_ROWS it is ignoring the hint completely).
    so the order of tables in the execution plan is important. How can I determine it ? I have read Tom's effective oracle by design but there is also no solution.

    Not sure I quite understand the question.
    Both threads contain lots of useful information about the broad considerations in play and debunking any myths.
    I need some help to understand the bold line, i.e.
    "so the order of tables in the execution plan is important"I read this as meaning just what it says, i.e. read the execution plan carefully and that
    NESTED LOOP
      A
      Bis not the same as
    NESTED LOOP
      B
      AA 10053 trace would normally be quite verbose about it's considerations as to join order.

  • Generally when does optimizer use nested loop and Hash joins  ?

    Version: 11.2.0.3, 10.2
    Lets say I have a table called ORDER and ORDER_DETAIL.
    ORDER_DETAIL is the child table of ORDERS .
    This is what I understand about Nested Loop:
    When we join ORDER AND ORDER_DETAIL tables oracle will form a 'nested loop' in which for each order_ID in ORDER table (outer loop), oracle will look for corresponding multiple ORDER_IDs in the ORDER_DETAIL table.
    Is nested loop used when the driving table (ORDER in this case) is smaller than the child table (ORDER_DETAIL) ?
    Is nested loop more likely to use Indexes in general ?
    How will these two tables be joined using Hash joins ?
    When is it ideal to use hash joins  ?

    Your description of a nested loop is correct.
    The overall rule is that Oracle will use the plan that it calculates to be, in general, fastest. That mostly means fewest I/O's, but there are various factors that adjust its calculation - e.g. it expects index blocks to be cached, multiple reads entries in an index may reference the same block, full scans get multiple blocks per I/O. It also has CPU cost calculations, but they generally only become significant with function / package calls or domain indexes (spatial, text, ...).
    Nested loop with an index will require one indexed read of the child table per outer table row, so its I/O cost is roughly twice the number of rows expected to match the where clause conditions on the outer table.
    A hash join reads the of the smaller table into a hash table then matches the rows from the larger table against the hash table, so its I/O cost is the cost of a full scan of each table (unless the smaller table is too big to fit in a single in-memory hash table). Hash joins generally don't use indexes - it doesn't use the index to look up each result. It can use an index as a data source, as a narrow version of the table or a way to identify the rows satisfying the other where clause conditions.
    If you are processing the whole of both tables, Oracle is likely to use a hash join, and be very fast and efficient about it.
    If your where clause restricts it to a just few rows from the parent table and a few corresponding rows from the child table, and you have an index Oracle is likely to use a nested loops solution.
    If the tables are very small, either plan is efficient - you may be surprised by its choice.
    Don't be worry about plans with full scans and hash joins - they are usually very fast and efficient. Often bad performance comes from having to do nested loop lookups for lots of rows.

  • LOOP and Read statements

    Hi abapers,
                        I want to know the difference between statements.
    SELECT MATNR MAKTX FROM MAKT INTO TABLE IT_MAKT.
    SELECT EBELN EBELP ... ..... ..... FROM EKPO INTO IT_EKPO WHERE MATNR = IT_MAKT-MATNR.
    1st statement
    LOOP AT IT_MAKT INTO WA_MAKT.
    READ TABLE IT_EKPO INTO WA_EKPO WITH KEY MATNR = IT_MAKT-MATNR.
    2ND Statement
    LOOP AT IT_EKPO INTO WA_EKPO.
    READ TABLE IT_MAKT INTO WA_MAKT WITH KEY MATNR  = IT_EKPO-MATNR.
    Frnds , can anyone please help me to understand the exact difference between the above statements.
    Thanks,
    satish

    Hi,
    SELECT MATNR MAKTX FROM MAKT INTO TABLE IT_MAKT.
    collects matnr and maktx form makt and stores in it_makt
    SELECT EBELN EBELP ... ..... ..... FROM EKPO INTO IT_EKPO WHERE MATNR = IT_MAKT-MATNR.
    endselect.
    selects ebeln and ebelp from  ekpo and stores in it_ekpo
    1st statement
    LOOP AT IT_MAKT INTO WA_MAKT.
    READ TABLE IT_EKPO INTO WA_EKPO WITH KEY MATNR = IT_MAKT-MATNR.
    endloop.
    looping at it_makt compares matnr from it_makt with it_ekpo. reads and stores in work area wa_makt with primary key as index
    2ND Statement
    LOOP AT IT_EKPO INTO WA_EKPO.
    READ TABLE IT_MAKT INTO WA_MAKT WITH KEY MATNR = IT_EKPO-MATNR.
    endloop.
    looping at it_ekpo compares matnr from it_makt with it_ekpo . reads and stores in work area wa_ekpo with primary key as index
    regards

  • Need nested loop's solution....

    hi..
    i have done following coding for my one senario..i've used nested loop.but can anyone pls give me other solution than nested loop statement?
    i dont wnat to use nested loop...
    SELECT WI_ID WI_STAT WI_CD WI_AAGENT FROM SWWWIHEAD           "FETCHING WORK ITEM DATA FROM THE SWWWIHEAD
        INTO TABLE IT_SWWWIHEAD
        WHERE WI_CD IN SO_WI_CD.
      SORT IT_SWWWIHEAD.
      IF SY-SUBRC = 0.
      <b>  LOOP AT IT_SWWWIHEAD INTO WA_SWWWIHEAD.</b>
          CALL FUNCTION 'SWI_GET_DEPENDENT_WORKITEMS'      "FUNCTION MODULE TO GET DEPENDENT WORK ITEM ID, IF ANY.
            EXPORTING
              WI_ID         = WA_SWWWIHEAD-WI_ID
            TABLES
              DEPENDENT_WIS = IT_SWWWIHEAD_D.
          IF IT_SWWWIHEAD_D IS NOT INITIAL.
            DELETE IT_SWWWIHEAD_D WHERE WI_TYPE <> 'W'.
            SORT IT_SWWWIHEAD_D.
          <b>  LOOP AT IT_SWWWIHEAD_D INTO WA_SWWWIHEAD_D.</b>
              CALL FUNCTION 'SAP_WAPI_READ_CONTAINER'          "FUNCTION MODULE TO GET DATA FROM EVERY DEPENDENT ID.
                EXPORTING
                  WORKITEM_ID                    = WA_SWWWIHEAD_D-WI_ID
                LANGUAGE                       = SY-LANGU
                USER                           = SY-UNAME
              IMPORTING
                RETURN_CODE                    =
                IFS_XML_CONTAINER              =
                IFS_XML_CONTAINER_SCHEMA       =
               TABLES
                 SIMPLE_CONTAINER               = IT_SIM_CONT
               MESSAGE_LINES                  =
               MESSAGE_STRUCT                 =
               SUBCONTAINER_BOR_OBJECTS       =
                SUBCONTAINER_ALL_OBJECTS       = IT_SUBCONTAINER
              READ TABLE IT_SIM_CONT
                  INTO WA_SIM_CONT WITH KEY ELEMENT = '_WI_RESULT'.        "getting the result(approved or rejected).
              IF SY-SUBRC = 0.
                IF wa_sim_cont-value = '0001'.
                  WA_FINAL-WI_STAT = 'APPROVED'.
                ELSEIF WA_SIM_CONT-VALUE = '0002'.
                  WA_FINAL-WI_STAT = 'REJECTED'.
                ENDIF.
              ENDIF.
              READ TABLE IT_SUBCONTAINER
                  INTO WA_SUBCONTAINER WITH KEY ELEMENT = 'SODATA'.  "getting SO DOCUMENT for this workitem.
              IF SY-SUBRC = 0.
                WA_FINAL-WI_AAGENT    = WA_SWWWIHEAD_D-WI_AAGENT.
              ENDIF.
                WA_FINAL-WI_ID        = WA_SWWWIHEAD-WI_ID.
                WA_FINAL-WI_ID_D      = WA_SWWWIHEAD_D-WI_ID.
                WA_FINAL-WI_CD        = WA_SWWWIHEAD-WI_CD.
                WA_FINAL-WI_SO        = wa_subcontainer-value+0(10).
                WA_FINAL-WI_RESULT    = WA_SIM_CONT-VALUE.
                SELECT SINGLE VKORG MAHDT FROM VBAK
                  INTO (VKORG, MAHDT)
                  WHERE VBELN = WA_FINAL-WI_SO.
                IF SY-SUBRC = 0.
                  WA_FINAL-WI_VKORG = VKORG.
                  IF MAHDT <> '00000000'.
                    WA_FINAL-WI_FINAL_RESULT = 'OK'.
                  ELSE.
                    WA_FINAL-WI_FINAL_RESULT = 'PENDING'.
                  ENDIF.
                ENDIF.
                APPEND WA_FINAL TO IT_FINAL.
                CLEAR WA_FINAL.
       <b>     ENDLOOP.</b>
            CLEAR IT_SWWWIHEAD_D[].
            CLEAR IT_SIM_CONT[].
          ENDIF.
      <b>  ENDLOOP.</b>  ENDIF.

    hi sagar,
    Pls go through the following explanations for understanding abt control level processing.
    Control level processing is allowed within a LOOP over an internal table. This means that you can divide sequences of entries into groups based on the contents of certain fields.
    Internal tables are divided into groups according to the sequence of the fields in the line structure. The first column defines the highest control level and so on. The control level hierarchy must be known when you create the internal table.
    The control levels are formed by sorting the internal table in the sequence of its structure, that is, by the first field first, then by the second field, and so on. Tables in which the table key occurs at the start of the table are particularly suitable for control level processing.
    The following diagram illustrates control level processing in a sorted table, where different field contents in the first three fields are indicated by different colors:
    Each change of color in a column indicates a control level change in the corresponding hierarchy level. Within the processing block of a loop, you can use the control level statement AT to react to a control level change. This enables you to restrict statements to a certain set of lines. You can thus use the SUM statement to calculate totals from subsets of all lines.
    The AT statement introduces a statement block that you end with the ENDAT statement.
    AT <level>.
      <statement block>
    ENDAT.
    You can react to the following control level changes:
    <level>
    Meaning
    FIRST
    First line of the internal table
    LAST
    Last line of the internal table
    NEW <f>
    Beginning of a group of lines with the same contents in the field <f> and in the fields left of <f>
    END Of <f>
    End of a group of lines with the same contents in the field <f> and in the fields left of <f>
    You can use control level statements to react to control breaks in internal tables instead of programming them yourself with logical expressions. Within the loop, you must order the AT-ENDAT statement blocks according to the hierarchy of the control levels. If the internal table has the columns <f1>, <f 2>, ...., and if it is sorted by these columns, you must program the loop as follows:
    LOOP AT <itab>.
      AT FIRST. ... ENDAT.
        AT NEW <f1>. ...... ENDAT.
          AT NEW <f2 >. ...... ENDAT.
              <single line processing>
          AT END OF <f2>. ... ENDAT.
        AT END OF <f1>. ... ENDAT.
      AT LAST. .... ENDAT.
    ENDLOOP.
    The innermost hierarchy level <single line processing> processes the table lines that do not correspond to a control level change. You do not have to use all control level statements. But you must place the used ones in the above sequence. You should not use control level statements in loops where the line selection is restricted by WHERE or FROM and TO. Neither should the table be modified during the loop.
    If a control level field <fi> is not known until runtime, you can specify it dynamically as (<n i>) where <n i> contains the field of <f i>. If <n i> is empty at runtime, the criterion for changing the control level is ignored. You can restrict the search to partial fields by specifying offset and length.
    If you are working with a work area <wa>, it does not contain the current line in the AT... ENDAT statement block. All character fields to the right of the current group key are filled with asterisks (*). All other fields to the right of the current group key contain their initial value.
    Within an AT...ENDAT block, you can calculate the contents of the numeric fields of the corresponding control level using the SUM statement.
    SUM.
    You can only use this statement within a LOOP. If you use SUM in an AT - ENDAT block, the system calculates totals for the numeric fields of all lines in the current line group and writes them to the corresponding fields in the work area (see example in ). If you use the SUM statement outside an AT - ENDAT block (single entry processing), the system calculates totals for the numeric fields of all lines of the internal table in each loop pass and writes them to the corresponding fields of the work area. It therefore only makes sense to use the SUM statement in AT...ENDAT blocks.
    If the table contains a nested table, you cannot use the SUM statement. Neither can you use it if you are using a field symbol instead of a work area in the LOOP statement.
    Examples
    DATA: BEGIN OF LINE,
             COL1 TYPE C,
             COL2 TYPE I,
             COL3 TYPE I,
          END OF LINE.
    DATA ITAB LIKE HASHED TABLE OF LINE
              WITH UNIQUE KEY COL1 COL2.
    LINE-COL1 = 'A'.
    DO 3 TIMES.
      LINE-COL2 = SY-INDEX.
      LINE-COL3 = SY-INDEX ** 2.
      INSERT LINE INTO TABLE ITAB.
    ENDDO.
    LINE-COL1 = 'B'.
    DO 3 TIMES.
      LINE-COL2 = 2 * SY-INDEX.
      LINE-COL3 = ( 2 * SY-INDEX ) ** 2.
      INSERT LINE INTO TABLE ITAB.
    ENDDO.
    SORT ITAB.
    LOOP AT ITAB INTO LINE.
      WRITE: / LINE-COL1, LINE-COL2, LINE-COL3.
      AT END OF COL1.
        SUM.
        ULINE.
        WRITE: / LINE-COL1, LINE-COL2, LINE-COL3.
        SKIP.
      ENDAT.
      AT LAST.
        SUM.
        ULINE.
        WRITE: / LINE-COL1, LINE-COL2, LINE-COL3.
      ENDAT.
    ENDLOOP.
    The output is:
    A 1 1
    A 2 4
    A          3          9
    A          6         14
    B          2          4
    B 4 16
    B 6 36
    B         12         56
            18         70
    The program creates a hashed table ITAB, fills it with six lines, and sorts it. In the LOOP - ENDLOOP block, the work area LINE is output for each loop pass. The first field of the table key, COL1, is used for control level processing. The total for all numeric fields is always calculated when the contents of COL1 change and when the system is in the last loop pass.
    DATA: BEGIN OF LINE,
            CARRID   TYPE SBOOK-CARRID,
            CONNID   TYPE SBOOK-CONNID,
            FLDATE   TYPE SBOOK-FLDATE,
            CUSTTYPE TYPE SBOOK-CUSTTYPE,
            CLASS    TYPE SBOOK-CLASS,
            BOOKID   TYPE SBOOK-BOOKID,
          END OF LINE.
    DATA ITAB LIKE SORTED TABLE OF LINE WITH UNIQUE KEY TABLE LINE.
    SELECT CARRID CONNID FLDATE CUSTTYPE CLASS BOOKID
           FROM SBOOK INTO CORRESPONDING FIELDS OF TABLE ITAB.
    LOOP AT ITAB INTO LINE.
      AT FIRST.
        WRITE / 'List of Bookings'.
        ULINE.
      ENDAT.
        AT NEW CARRID.
          WRITE: / 'Carrid:', LINE-CARRID.
        ENDAT.
          AT NEW CONNID.
            WRITE: / 'Connid:', LINE-CONNID.
          ENDAT.
            AT NEW FLDATE.
              WRITE: / 'Fldate:', LINE-FLDATE.
            ENDAT.
              AT NEW CUSTTYPE.
                WRITE: / 'Custtype:', LINE-CUSTTYPE.
              ENDAT.
                   WRITE: / LINE-BOOKID, LINE-CLASS.
                AT END OF CLASS.
                  ULINE.
                ENDAT.
    ENDLOOP.
    In this example, the sorted internal table ITAB is filled with data from the database table SBOOK using the Open SQL statement SELECT. The sequence of the columns in the internal table defines the control level hierarchy. Since the table key is the entire line, the sort sequence and the control level hierarchy are the same. The sequence of the AT-ENDAT blocks within the LOOP and ENDLOOP statements is important.
    The output is as follows:
    List of Bookings
    Carrid: AA
    Connid: 0017
    Fldate: 1998/11/22
    Custtype: B
    00063509 C
    00063517 C
    00063532 F
    00063535 F
    Custtype: P
    00063653 C
    00063654 C
    00063668 F
    00063670 F
    Fldate: 1998/29/11
    Custtype: B
    00064120 C
    00064121 C
    and so on.
    <b>pls reward if helpful.</b>

  • SAP QUERY LOOPS AND INTERNAL TABLE

    Hi All, I have a query which i have made. It runs from Table EKPO which has PO details and what I want to do is now via ABAP Code pull through the total of goods receipt for the PO and Line Item into a field. Sounds Easy enough..Problem now,
    The table which contains the GR data is EKBE which agains a PO and Line Item can have many 101 movements and 102 movements so what I want is an ABAP Statent to basically sum up the total of 101 for the PO & LINE ITEMS and then minus this from the total of 102 for the PO & LINE ITEMS and post the result in to this new field I have created.
    I am pretty decent with ABAP Code in Querys I.e Select statements etc but from what I can see i need to create an internal table and do a loop and collect statement but I keep on failing due to not enough knowledge. Please can some one help me with this and provide me with the code and explanation as i would like to understand,
    POINTS WILL BE REWARDED
    Thanks
    Kind Regards
    Adeel Sarwar

    Hi,
    This is the full code i have entered but its not working. Any help would be appreciated. If you could rectify the code and internal tables that would be great.
    Thanks
    TABLES: EKBE.
    DATA: PurO LIKE EKPO-EBELN,
          POLI LIKE EKPO-EBELP.
    *New Table and Vars defined
    DATA:   BEGIN OF IT_EKBE,
              IT_EKBE LIKE EKBE,
            END OF IT_EKBE.
    DATA:  BEGIN OF IT_SUM OCCURS 0,
              EBELN TYPE EBELN,
              EBELP TYPE EBELP,
              DMBTR TYPE DMBTR,
              MENGE TYPE MENGE,
          END OF IT_SUM.
    CLEAR: QTYD.
    MOVE: EKPO-EBELN TO PurO,
          EKPO-EBELP TO POLI.
    SELECT * FROM EKBE INTO IT_EKBE
        WHERE EBELN = PurO
        AND   EBELP = POLI
        AND   BEWTP = 'E'
    LOOP AT IT_EKBE.
      MOVE CORRESPOING IT_EKBE TO IT_SUM.
      IF IT_EKBE-BWART = '102'.
        IT_SUM-DMBTR = IT_SUM-DMBTR * -1.
        IT_SUM-MENGE = IT_SUM-MENGE * -1.
      ENIDF.
      COLLECT IT_SUM.
      CLEAR IT_SUM.
    ENDLOOP.
    ENDSELECT.
    If sy-subrc = 0.
      QTYD = IT_SUM.
    ELSE.
      QTYD = 0.
    ENDIF.

  • Nested loop, merge join and harsh join

    Can any one tell me the difference/relationship between nested loop, harsh join and merge join...Thanx

    Check Oracle Performance Tuning Guide
    13.6 Understanding Joins
    http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i51523

  • Loop through nested elements and insert via PL/SQL

    INSERT INTO Orders(id, OrderXML) VALUES
    (S_Orders.Nextval,
    '<?xml version="1.0" encoding="utf-8" ?>
    <Order xmlns="urn:foo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:foo foo-1.xsd">
    <OrderRef>BBB</OrderRef>
    <OrderDate>2005-03-29</OrderDate>
    <CustomerID>1051</CustomerID>
    <Items>
    <Item>
    <ProductID>7</ProductID>
    <Price>45.6</Price>
    <Quantity>2</Quantity>
    </Item>
    <Item>
    <ProductID>19</ProductID>
    <Price>73.5</Price>
    <Quantity>10</Quantity>
    </Item>
    </Items>
    </Order>'
    I some questions regarding index search of nested elements like,Items in the above example.
    I would like to know how I can LOOP through the Items like 1..2 LOOP
    and insert those elements(item) into one table. Order information should go in to another table.
    Can this be done with xpath and PL/SQL.
    Regards
    Ulf

    Hi Marco!
    Here's some more information:
    CREATE TABLE ITEM (ProductID NUMBER,
    Price NUMBER(8,2)
    Quantity 10 NUMBER);
    CREATE TABLE ORDER (OrderRef VARCHAR2(10),
    ORDER_DATE VARCHAR2(10),
    CUSTOMERID NUMBER);
    The main problem that I have is to create an solution that can be dynamic so that I can have for instance one order and four items in one XML.
    The second XML can have one order and 10 items.
    First I want to insert the order elements in the order table and then the items records in the item table.
    To complicate things futher my real XML have namespaces in the XML, but this I think I can handle.
    Summary: So for each order row(element) I want to traverse the Item elements and insert them to the Item table.
    Regards
    /Ulf

  • How to write select statement before the loop and how to use read statemnt

    Hi,
    Recently our system has changed from 4.6 to ECC6.
    As its migrated its showing lots of errors like in between loop and endloop there should be no select statemnt........
    Can any one please tell how to write that coding in ECC6 , how can i change the code......
    In between loop and endloop i am having lots of select statemnts.....ple tell thye coding how can i select before the loop starts and
    how to read that internal table in loop.

    Hi Deepthi,
    You can do as per below:
    1) Select the required entries from the tables you need (VBAK, VBAP, KNA1, etc)
    SELECT VBELN ERDAT KUNNR
        into table it_vbak
        from VBAK
    where VBELN = S_VBELN. "Selection criteria
    If sy-subrc = 0.
    SELECT VBELN POSNR MATNR
        into table it_vbap
        from VBAP
    for all entries in it_vbak
    where VBELN = it_vbak-vbeln
    SELECT KUNNR NAME1
        into table it_vbak
        from VBAK
    where VBELN = it_vbak-vbeln.
    endif.
    2) Loop at the entries, and read internal table it-kna1 for customer info.
    Loop at it_vbak into wa_vbak.
    read table it_kna1 into wa_kna1 with key kunnr = wa_vbak-kunnr.
    if sy-subrc = 0.
    endif.
    loop at it_vbap into wa_vbap where vbeln = wa_vbak-vbeln.
    endloop.
    endloop.
    This is the basic idea and short example of how to extract entries and read internal table.
    Hope this helps.
    Regards,
    Patrick

  • Problem with Nested loop in Fox-Formula

    Dear Experts,
    Let s share the scenario :
    MaterialGroups with following Keys for Example AAAA, BBBB, CCCC..., Materialgroups are selected in the 1st input ready query, which is assigned to DataProvider DP_1 in a  webtemplate.
    every Materialgroup has several Materials, for instance:
    Materialgroup AAAA has following Materials: AAAA10, AAAA11, AAAA12, AAAA13...
    Materials are  selected in a second  input ready Query, which is assigned to a second DataProvider DP_2 in the Same Webtemplate as the query 1.
    Both Materialgroup and Material are based on the same Aggreagtion level and same real time cube.
    I want to copy the input values for every  MaterialGroup ( 1st query, DP_1) only to it s own Materials (2cond Query, DP_2).
    To resolve this Issue i wrote the following Fox Formula code with a nested loop, however it does not work properly. when I m debugging the code, i could release that the second Loop was ignored.but wehn i replace the second loop (nested loop) with a fixed value it s seems to work properly
    DATA MG1 TYPE MATG.<------ MaterialGroup
    DATA MT1 TYPE MAT.<----
    Material
    DATA S1 TYPE STRING.
    DATA S2 TYPE STRING.
    DATA S3 TYPE STRING
    DATA K TYPE F.
    DATA Z TYPE F.
    FOREACH MG1.
    To check Materialgroup in debugger
    S1= MG1.
    BREAK-POINT.
    K = {KEYfIG, #, MG1}.
    BREAK-POINT.
    FOREACH  MT1.   <----- if i set MT1 to a fixed value like AAAA11 then S3 get the wished value namely AAAA
    S2 = MT1.
    BREAK-POINT.
    S3 =  SUBSTR (MT1, 0, 4).  
    BREAK-POINT.
    IF S1 = S3.
    {KEYFIG, MT1, #} = K.
    following Statement is only used To check in debugger if Material has become the same Materialgroup value
    Z = {KEYFIG, MT1, #}.
    BREAK-POINT.
    ENDIF.
    ENDFOR.
    ENDFOR.
    Thakns for any help
    Frank
    Edited by: FRYYYBM on Mar 17, 2011 10:54 PM
    Edited by: FRYYYBM on Mar 17, 2011 11:06 PM

    Hi,
    Please try this way.
    DATA MG1 TYPE MATG.<------ MaterialGroup
    DATA MT1 TYPE MAT.<----
    Material
    DATA S1 TYPE STRING.
    DATA S2 TYPE STRING.
    DATA S3 TYPE STRING
    DATA K TYPE F.
    DATA Z TYPE F.
    FOREACH MT1.
    FOREACH MG1.
    To check Materialgroup in debugger
    S1= MG1.
    BREAK-POINT.
    K = {KEYfIG, #, MG1}.
    BREAK-POINT.
    FOREACH MT1. <----- if i set MT1 to a fixed value like AAAA11 then S3 get the wished value namely AAAA
    S2 = MT1.
    BREAK-POINT.
    S3 = SUBSTR (MT1, 0, 4).
    BREAK-POINT.
    IF S1 = S3.
    {KEYFIG, MT1, #} = K.
    following Statement is only used To check in debugger if Material has become the same Materialgroup value
    Z = {KEYFIG, MT1, #}.
    BREAK-POINT.
    ENDIF.
    ENDFOR.
    ENDFOR.
    ENDFOR.
    Thanks.
    With regards,
    Anand Kumar

  • Too many nested loops in execution plan?

    Hi,
    i wonder about execution plan not indicating that access to some tables (for join) is in parallel.
    Please see this example:
    ------------------------ snip ------------------------------------
    drop table test_a1;
    drop table test_a2;
    drop table test_b;
    drop table test_c;
    drop table test_d;
    create table test_a1 (
    x number,
    y number,
    z number);
    create unique index testa1_pk on test_a1 (x);
    create table test_a2 (
    x number,
    y number,
    z number);
    create unique index testa2_pk on test_a2 (x);
    create table test_b (
    x number,
    y number,
    z number);
    create unique index testb_pk on test_b (y);
    create table test_c (
    x number,
    y number,
    z number);
    create unique index testc_pk on test_b (z);
    create table test_d (
    x number,
    y number,
    z number);
    create unique index testd_pk on test_d (y);
    select
    a1.x a1_x,
    a1.y a1_y,
    a1.z a1_z,
    a2.x a2_x,
    a2.y a2_y,
    a2.z a2_z,
    b.x b_x,
    b.y b_y,
    b.z b_z,
    c.x c_x,
    c.y c_y,
    c.z c_z,
    d.x d_x,
    d.y d_y,
    d.z d_z
    from test_a1 a1, test_a2 a2, test_b b, test_c c, test_d d
    where a1.x = 100
    and a2.x = 200
    and b.y = a1.y
    and c.z = b.z
    and d.y = a1.y;
    ------------------------ snap ------------------------------------
    The execution plan goes like this:
    Select Stmt
         nested loops
              nested loops
                   nested loops
                        nested loops
                             table access
                                  index
                                       access predicate
                                            a2.x = 200
                             table access
                                  index
                                       access predicate
                                            a1.x = 100
                        table access
                             index
                                  access predicate
                                       d.y = a1.y
                   table access
                        index
                             access predicate
                                  b.y = a1.y
              table acess
                   index
                        acess predicate
                             c.z = b.z
    Access to tables a1 and a2 is on the same level (in parallel - i guess).
    However, why isn't access to table d and b on the same level?
    Both depend on a1. So no need to execute one after the other (no inter-dependency).
    Maybe i have just wrong expectation to the output of the execution plan(?!)
    - many thanks!
    best regards,
    Frank

    Preservation of identation and spacing is invaluable when it comes to reading an explain plan.
    | Id  | Operation                       | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                |           |     1 |   195 |     2   (0)| 00:00:01 |
    |   1 |  NESTED LOOPS                   |           |     1 |   195 |     2   (0)| 00:00:01 |
    |   2 |   NESTED LOOPS                  |           |     1 |   156 |     0   (0)| 00:00:01 |
    |   3 |    NESTED LOOPS                 |           |     1 |   117 |     0   (0)| 00:00:01 |
    |   4 |     NESTED LOOPS                |           |     1 |    78 |     0   (0)| 00:00:01 |
    |   5 |      TABLE ACCESS BY INDEX ROWID| TEST_A2   |     1 |    39 |     0   (0)| 00:00:01 |
    |*  6 |       INDEX UNIQUE SCAN         | TESTA2_PK |     1 |       |     0   (0)| 00:00:01 |
    |   7 |      TABLE ACCESS BY INDEX ROWID| TEST_A1   |     1 |    39 |     0   (0)| 00:00:01 |
    |*  8 |       INDEX UNIQUE SCAN         | TESTA1_PK |     1 |       |     0   (0)| 00:00:01 |
    |   9 |     TABLE ACCESS BY INDEX ROWID | TEST_D    |    82 |  3198 |     0   (0)| 00:00:01 |
    |* 10 |      INDEX UNIQUE SCAN          | TESTD_PK  |     1 |       |     0   (0)| 00:00:01 |
    |  11 |    TABLE ACCESS BY INDEX ROWID  | TEST_B    |    82 |  3198 |     0   (0)| 00:00:01 |
    |* 12 |     INDEX UNIQUE SCAN           | TESTB_PK  |     1 |       |     0   (0)| 00:00:01 |
    |* 13 |   TABLE ACCESS FULL             | TEST_C    |     1 |    39 |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       6 - access("A2"."X"=200)
       8 - access("A1"."X"=100)
      10 - access("D"."Y"="A1"."Y")
      12 - access("B"."Y"="A1"."Y")
      13 - filter("C"."Z"="B"."Z")
    Access to tables a1 and a2 is on the same level (in parallel - i guess).
    Maybe i have just wrong expectation to the output of the execution plan(?!)You guess wrong, there's nothing parallel going on here.
    Execution plan is a tree of parent-child operations.
    For example, the NESTED LOOP at operation 4 has two children @ 5 and 7.
    Both of these operations- 5 & 7 - have a single child operation.
    The execution tree starts with operation 6, using the TESTA2_PK index to identify rows where A2.X=100.
    From this list of rowids, we go to the table TEST_A2 operation 5.
    The rows from operation five feed into the NESTED LOOP - operation 4.
    For each of these rows, we go to TEST_A1 via the index TEST_A1_PK for rows where A1.X=100.
    This is really a cartesian join because there's no join condition between the two tables.
    etc, etc, etc
    Three things in particular to point out.
    Firstly, that nothing joins to A2. So there will be a cartesian product - i.e. for every row in the result set between the joined tables A1, B, C and D, these will be multiplied by the number of rows returned by the the A2 rowsource.
    Secondly, when everything has got one or zero rows (or the optimizer thinks that it's one or zero rows), you can get very different plans from when there are known/thought to be more rows.
    Both depend on a1. So no need to execute one after the other (no inter-dependency).Thirdly, in terms of isolated join operations (ignoring A2 and C for the moment), A1 cannot join to B and D at the same time, you can either join A1 to B and then join the result of that to D, or join A1 to D then B, which is what you've got in your plan (well, actually we have A2 joined to A1 then the result of that joined to D and then the result of that to B).
    Edited by: Dom Brooks on Jul 6, 2011 4:07 PM
    Corrected typo

  • Why optimizer prefers nested loop over hash join?

    What do I look for if I want to find out why the server prefers a nested loop over hash join?
    The server is 10.2.0.4.0.
    The query is:
    SELECT p.*
        FROM t1 p, t2 d
        WHERE d.emplid = p.id_psoft
          AND p.flag_processed = 'N'
          AND p.desc_pool = :b1
          AND NOT d.name LIKE '%DUPLICATE%'
          AND ROWNUM < 2tkprof output is:
    Production
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.01       0.00          0          0          4           0
    Execute      1      0.00       0.01          0          4          0           0
    Fetch        1    228.83     223.48          0    4264533          0           1
    total        3    228.84     223.50          0    4264537          4           1
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 108  (SANJEEV)
    Rows     Row Source Operation
          1  COUNT STOPKEY (cr=4264533 pr=0 pw=0 time=223484076 us)
          1   NESTED LOOPS  (cr=4264533 pr=0 pw=0 time=223484031 us)
      10401    TABLE ACCESS FULL T1 (cr=192 pr=0 pw=0 time=228969 us)
          1    TABLE ACCESS FULL T2 (cr=4264341 pr=0 pw=0 time=223182508 us)Development
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.01       0.00          0          0          0           0
    Execute      1      0.00       0.01          0          4          0           0
    Fetch        1      0.05       0.03          0        512          0           1
    total        3      0.06       0.06          0        516          0           1
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 113  (SANJEEV)
    Rows     Row Source Operation
          1  COUNT STOPKEY (cr=512 pr=0 pw=0 time=38876 us)
          1   HASH JOIN  (cr=512 pr=0 pw=0 time=38846 us)
         51    TABLE ACCESS FULL T2 (cr=492 pr=0 pw=0 time=30230 us)
        861    TABLE ACCESS FULL T1 (cr=20 pr=0 pw=0 time=2746 us)

    sanjeevchauhan wrote:
    What do I look for if I want to find out why the server prefers a nested loop over hash join?
    The server is 10.2.0.4.0.
    The query is:
    SELECT p.*
    FROM t1 p, t2 d
    WHERE d.emplid = p.id_psoft
    AND p.flag_processed = 'N'
    AND p.desc_pool = :b1
    AND NOT d.name LIKE '%DUPLICATE%'
    AND ROWNUM < 2
    You've got already some suggestions, but the most straightforward way is to run the unhinted statement in both environments and then force the join and access methods you would like to see using hints, in your case probably "USE_HASH(P D)" in your production environment and "FULL(P) FULL(D) USE_NL(P D)" in your development environment should be sufficient to see the costs and estimates returned by the optimizer when using the alternate access and join patterns.
    This give you a first indication why the optimizer thinks that the chosen access path seems to be cheaper than the obviously less efficient plan selected in production.
    As already mentioned by Hemant using bind variables complicates things a bit since EXPLAIN PLAN is not reliable due to bind variable peeking performed when executing the statement, but not when explaining.
    Since you're already on 10g you can get the actual execution plan used for all four variants using DBMS_XPLAN.DISPLAY_CURSOR which tells you more than the TKPROF output in the "Row Source Operation" section regarding the estimates and costs assigned.
    Of course the result of your whole exercise might be highly dependent on the actual bind variable value used.
    By the way, your statement is questionable in principle since you're querying for the first row of an indeterministic result set. It's not deterministic since you've defined no particular order so depending on the way Oracle executes the statement and the physical storage of your data this query might return different results on different runs.
    This is either an indication of a bad design (If the query is supposed to return exactly one row then you don't need the ROWNUM restriction) or an incorrect attempt of a Top 1 query which requires you to specify somehow an order, either by adding a ORDER BY to the statement and wrapping it into an inline view, or e.g. using some analytic functions that allow you specify a RANK by a defined ORDER.
    This is an example of how a deterministic Top N query could look like:
    SELECT
    FROM
    SELECT p.*
        FROM t1 p, t2 d
        WHERE d.emplid = p.id_psoft
          AND p.flag_processed = 'N'
          AND p.desc_pool = :b1
          AND NOT d.name LIKE '%DUPLICATE%'
    ORDER BY <order_criteria>
    WHERE ROWNUM <= 1;Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Nested loop vs Hash Join

    Hi,
    Both the querys are returning same results, but in my first query hash join and second query nested loop . How ? PLs explain
    select *
    from emp a,dept b
    where a.deptno=b.deptno and b.deptno>20;
    6 rows
    Plan hash value: 4102772462
    | Id  | Operation                    | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT             |         |     6 |   348 |     6  (17)| 00:00:01 |
    |*  1 |  HASH JOIN                   |         |     6 |   348 |     6  (17)| 00:00:01 |
    |   2 |   TABLE ACCESS BY INDEX ROWID| DEPT    |     3 |    60 |     2   (0)| 00:00:01 |
    |*  3 |    INDEX RANGE SCAN          | PK_DEPT |     3 |       |     1   (0)| 00:00:01 |
    |*  4 |   TABLE ACCESS FULL          | EMP     |     7 |   266 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - access("A"."DEPTNO"="B"."DEPTNO")
       3 - access("B"."DEPTNO">20)
       4 - filter("A"."DEPTNO">20)
    select *
    from emp a,dept b
    where a.deptno=b.deptno and b.deptno=30;  
    6 rows
    Plan hash value: 568005898
    | Id  | Operation                    | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT             |         |     5 |   290 |     4   (0)| 00:00:01 |
    |   1 |  NESTED LOOPS                |         |     5 |   290 |     4   (0)| 00:00:01 |
    |   2 |   TABLE ACCESS BY INDEX ROWID| DEPT    |     1 |    20 |     1   (0)| 00:00:01 |
    |*  3 |    INDEX UNIQUE SCAN         | PK_DEPT |     1 |       |     0   (0)| 00:00:01 |
    |*  4 |   TABLE ACCESS FULL          | EMP     |     5 |   190 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       3 - access("B"."DEPTNO"=30)
       4 - filter("A"."DEPTNO"=30)

    Hi,
    Unless specifically requested, Oracle picks the best execution plan based on estimates of table sizes, column selectivity and many other variables. Even though Oracle does its best to have the estimates as accurate as possible, they are frequently different, and in some cases quite different, from the actual values.
    In the first query, Oracle estimated that the predicate “ b.deptno>20” would limit the number of records to 6, and based on that it decided the use Hash Join.
    In the second query, Oracle estimated that the predicate “b.deptno=30” would limit the number of records to 5, and based on that it decided the use Nested Loops Join.
    The fact that the actual number of records is the same is irrelevant because Oracle used the estimate, rather the actual number of records to pick the best plan.
    HTH,
    Iordan
    Iotzov

  • HASH JOIN or NESTED LOOP

    I've been asked to check if HASH JOIN is more suitable than NESTED LOOP(which CBO chose by default) for the following query.
    SELECT CM_DETAILS.TASK_ID FROM GEN_TYPE, CM_DETAILS WHERE ( ( ( ( ( CM_DETAILS.STAT_CODE < 8 ) AND ( GEN_TYPE.TASK_ID = CM_DETAILS.TASK_ID ) ) AND ( GEN_TYPE.DEST_LOCN_ID = 5 ) ) AND ( GEN_TYPE.COM_ID = 7 ) ) AND ( ( ( CM_DETAILS.CASE_NO = 1 ) OR ( CM_DETAILS.CASE_NO = 3 ) ) OR ( CM_DETAILS.CASE_NO = 9 ) ) )
    Both GEN_TYPE and CM_DETAILS tables have over 330,000 rows.
    Version: 10g R2
    Any thoughts?

    As gintsp gave you very nice tip but there is initialization parameter "     OPTIMIZER_INDEX_COST_ADJ" which cause what path to be chose for CBO,but usually expert says for changing init paramter setting should be at last resort.
    It has default value of 100 which indicates to the CBO that indexed access is 100% as costly (i.e., equally costly) as FULL table scan access.
    SQL> column plan_plus_exp format a100
    SQL> set linesize 1000
    SQL> SET AUTOTRACE TRACEONLY
    SQL> SELECT e.ename,d.dname
      2    FROM emp e,dept d
      3   WHERE e.deptno=d.deptno
      4  /
    14 rows selected.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=7 Card=10 Bytes=320)
       1    0   HASH JOIN (Cost=7 Card=10 Bytes=320)
       2    1     TABLE ACCESS (FULL) OF 'DEPT' (TABLE) (Cost=3 Card=5 Bytes=90)
       3    1     TABLE ACCESS (FULL) OF 'EMP' (TABLE) (Cost=3 Card=14 Bytes=196)
    Statistics
            672  recursive calls
              0  db block gets
            151  consistent gets
             27  physical reads
              0  redo size
            793  bytes sent via SQL*Net to client
            508  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
             15  sorts (memory)
              0  sorts (disk)
             14  rows processed
    SQL> /
    14 rows selected.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=7 Card=10 Bytes=320)
       1    0   HASH JOIN (Cost=7 Card=10 Bytes=320)
       2    1     TABLE ACCESS (FULL) OF 'DEPT' (TABLE) (Cost=3 Card=5 Bytes=90)
       3    1     TABLE ACCESS (FULL) OF 'EMP' (TABLE) (Cost=3 Card=14 Bytes=196)
    Statistics
              0  recursive calls
              0  db block gets
             15  consistent gets
              0  physical reads
              0  redo size
            793  bytes sent via SQL*Net to client
            508  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
             14  rows processed
    SQL> SHOW PARAMETER optimizer
    NAME                                 TYPE                             VALUE
    optimizer_dynamic_sampling           integer                          2
    optimizer_features_enable            string                           10.1.0
    optimizer_index_caching              integer                          0
    optimizer_index_cost_adj             integer                          100<--------
    optimizer_mode                       string                           ALL_ROWS
    SQL> ALTER SESSION SET optimizer_index_cost_adj=35
      2  /
    Session altered.
    SQL> SELECT e.ename,d.dname
      2    FROM emp e,dept d
      3   WHERE e.deptno=d.deptno
      4  /
    14 rows selected.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=5 Card=10 Bytes=320)
       1    0   MERGE JOIN (Cost=5 Card=10 Bytes=320)
       2    1     TABLE ACCESS (BY INDEX ROWID) OF 'DEPT' (TABLE) (Cost=1 Card=5 Bytes=90)
       3    2       INDEX (FULL SCAN) OF 'DEPT_PRIMARY_KEY' (INDEX (UNIQUE)) (Cost=1 Card=5)
       4    1     SORT (JOIN) (Cost=4 Card=14 Bytes=196)
       5    4       TABLE ACCESS (FULL) OF 'EMP' (TABLE) (Cost=3 Card=14 Bytes=196)
    Statistics
              1  recursive calls
              0  db block gets
             11  consistent gets
              1  physical reads
              0  redo size
            733  bytes sent via SQL*Net to client
            508  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             14  rows processed
    SQL> /
    14 rows selected.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=5 Card=10 Bytes=320)
       1    0   MERGE JOIN (Cost=5 Card=10 Bytes=320)
       2    1     TABLE ACCESS (BY INDEX ROWID) OF 'DEPT' (TABLE) (Cost=1 Card=5 Bytes=90)
       3    2       INDEX (FULL SCAN) OF 'DEPT_PRIMARY_KEY' (INDEX (UNIQUE)) (Cost=1 Card=5)
       4    1     SORT (JOIN) (Cost=4 Card=14 Bytes=196)
       5    4       TABLE ACCESS (FULL) OF 'EMP' (TABLE) (Cost=3 Card=14 Bytes=196)
    Statistics
              0  recursive calls
              0  db block gets
             11  consistent gets
              0  physical reads
              0  redo size
            733  bytes sent via SQL*Net to client
            508  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             14  rows processedKhurram

Maybe you are looking for

  • No display after sleep with macmini using DVI - S-video/composite under XP

    Hi guys, I have installed XP on my mini. I have CRT TV so I'm using DVI -> S-video/composite to output to my TV. The problem is after sleep - there is no display (it's woking only after reset). I installed the latest drivers from the mac os 10.5 DVD

  • Forcing customers to pay for a phone and/or data package they don't want or need

    By their practices Verizon is forcing customers to pay for more than what the customer wants or needs, and at the same time giving the customer less of what they want or need. I've been a Verizon Wireless customer for years. Everytime my 2 year upgra

  • Cricket Wireless and WRT54G2

    i want to know if there is any way to use the WRT54G2 router together with cricket wireless.i have 2 laptops.one doesnt have a CD ROM drive so i cant install my cricket wireless broadband CD.Since i couldnt do that i connected an ethernet coard from

  • Currency decimal error

    Hi Team, We have created PR in USD and released. We have converted this PR to PO in JPY currency. Net price is displaying without currency decimal in JPY currency. When we display the print preview, system is automatically considering the last two di

  • Facetime not working on new OS 10.8.5

    facetime not working on new OS 10.8.5