Avoiding Nested Loops

Hi all,
I want to populate a internal table with Header and Item Level Details. BKPF is the Header Table and BSEG is the Item Details table. Can this be done without using nested LOOPS?
Consider the Logic I am using.
  SELECT bukrs
         belnr
         gjahr
         budat
         xblnr
         bktxt
         FROM   bkpf
         INTO TABLE t_bkpf
         WHERE      bukrs   IN p_bukrs " = p_bukrs
             AND    gjahr   IN p_gjahr  "= p_gjahr
             AND    monat   IN p_monat  " = p_monat
             AND    bstat    = space.
  IF sy-subrc IS INITIAL.
    SORT t_bkpf BY bukrs belnr gjahr.
    SELECT  bukrs
            belnr
            buzei
            gjahr
            hkont
            zlsch
            shkzg
            dmbtr
            FROM bseg
            INTO TABLE t_bseg
            FOR ALL ENTRIES IN t_bkpf
            WHERE     bukrs = t_bkpf-bukrs
               AND    gjahr = t_bkpf-gjahr
               AND    belnr = t_bkpf-belnr
               AND    hkont = w_hkont .
    IF sy-subrc IS INITIAL.
      SORT t_bseg BY  bukrs belnr gjahr buzei.
    ENDIF.
  ENDIF.
LOOP AT t_bkpf INTO wa_bkpf.
  LOOP AT t_bkpf INTO wa_bkpf WHERE bukrs = wa_bkpf-bukrs
                              AND   belnr = wa_bkpf-belnr
                              AND   gjahr = wa_bkpf-gjahr.
      wa_final-bukrs    =  wa_bkpf-bukrs.
      wa_final-budat    =  wa_bkpf-budat.
      wa_final-belnr    =  wa_bkpf-belnr.
      wa_final-shkzg    =  wa_bseg-shkzg.
      wa_final-dmbtr    =  wa_bseg-dmbtr.
      wa_final-xblnr    =  wa_bkpf-xblnr.
      wa_final-bktxt    =  wa_bkpf-bktxt.
      wa_final-hkont    =  wa_bseg-hkont.
      wa_final-zlsch    =  wa_bseg-zlsch.
   ENDLOOP.
ENDLOOP.
Thanks in advance.

Hai Arun try with the following code
  SELECT
         bukrs
         belnr
         gjahr
         budat
         xblnr
         bktxt
         FROM   bkpf
         INTO TABLE t_bkpf
         WHERE   bukrs   IN p_bukrs " = p_bukrs
             AND gjahr   IN p_gjahr  "= p_gjahr
             AND monat   IN p_monat  " = p_monat
             AND bstat    = space.
  IF sy-subrc IS INITIAL.
     SORT t_bkpf BY bukrs belnr gjahr.
  endif.
  if not t_bkpf[] is initial. 
    SELECT 
            bukrs
            belnr
            buzei
            gjahr
            hkont
            zlsch
            shkzg
            dmbtr
            FROM bseg
            INTO TABLE t_bseg
            FOR ALL ENTRIES IN t_bkpf
            WHERE     bukrs = t_bkpf-bukrs
               AND    belnr = t_bkpf-belnr
               AND    gjahr = t_bkpf-gjahr
               AND    hkont = w_hkont .
    IF sy-subrc IS INITIAL.
      SORT t_bseg BY  bukrs belnr gjahr buzei.
    ENDIF.
loop at t_bkpf.
  read table it_bseg with key   bukrs = t_bkpf-bukrs
                         AND    belnr = t_bkpf-belnr
                         AND    gjahr = t_bkpf-gjahr
                         binary search. 
  if sy-subrc = 0.
    wa_final-bukrs    =  wa_bkpf-bukrs.
    wa_final-budat    =  wa_bkpf-budat.
    wa_final-belnr    =  wa_bkpf-belnr.
    wa_final-shkzg    =  wa_bseg-shkzg.
    wa_final-dmbtr    =  wa_bseg-dmbtr.
    wa_final-xblnr    =  wa_bkpf-xblnr.
    wa_final-bktxt    =  wa_bkpf-bktxt.
    wa_final-hkont    =  wa_bseg-hkont.
    wa_final-zlsch    =  wa_bseg-zlsch.
  endif.
endloop. 
Thanks & regards
Sreenivasulu P

Similar Messages

  • Hi how to avoid nested loops in this program to improve the performence

    Hi all
    How to avoide the nested loops in this programing what is the replacement for the nested loops in this program coding......
    LOOP AT itb_ekpo.
        READ TABLE itb_marc WITH KEY
           matnr = itb_ekpo-matnr
           werks = itb_ekpo-werks BINARY SEARCH.
        CHECK sy-subrc = 0.
    FAE 26446 fin remplacement
        itb_pca-ebeln = itb_ekpo-ebeln.
        itb_pca-ebelp = itb_ekpo-ebelp.
      itb_pca-lifnr = itb_ekko-lifnr.   "-FAE26446
        itb_pca-lifnr = itb_ekpo-lifnr.                         "+FAE26446
        itb_pca-ekgrp = itb_ekpo-ekgrp.                         "+FAE26446
        itb_pca-dispo = itb_ekpo-dispo.                         "+FAE26446
        itb_pca-matnr = itb_ekpo-matnr.
        itb_pca-werks = itb_ekpo-werks.
      Recherche du libellé article
        READ TABLE itb_makt
                   WITH KEY matnr = itb_ekpo-matnr
                            spras = text-fra
                   BINARY SEARCH.
        IF sy-subrc = 0.
          itb_pca-maktx = itb_makt-maktx.
        ELSE.
          READ TABLE itb_makt
                    WITH KEY matnr = itb_ekpo-matnr
                             spras = text-ang
                    BINARY SEARCH.
          IF sy-subrc = 0.
            itb_pca-maktx = itb_makt-maktx.
          ENDIF.
        ENDIF.
        IF NOT itb_ekpo-bpumn IS INITIAL.
          itb_pca-menge = itb_ekpo-menge * itb_ekpo-bpumz /
                                           itb_ekpo-bpumn.
        ENDIF.
      Sélect° ds la table EKES des dates de livraisons et des qtés
      en transit
        CLEAR w_temoin_ar.
        CLEAR w_etens.
        LOOP AT itb_ekes
                FROM w_index_ekes.
          IF  itb_ekes-ebeln = itb_ekpo-ebeln
          AND itb_ekes-ebelp = itb_ekpo-ebelp.
            IF itb_ekes-ebtyp = text-arn.
              itb_pca-eindt = itb_ekes-eindt.
              w_temoin_ar = 'X'.
            ELSE.
            Si c'est une qté en transit alors on recupere
            la quantité et la date.
              IF itb_ekes-dabmg < itb_ekes-menge.
                itb_pca-qtran = itb_pca-qtran + itb_ekes-menge -
                                itb_ekes-dabmg.
              ENDIF.
              IF itb_ekes-etens > w_etens.
                w_etens = itb_ekes-etens.
                itb_pca-dtran = itb_ekes-eindt.
              ENDIF.
            ENDIF.
          ELSEIF itb_ekes-ebeln > itb_ekpo-ebeln
          OR ( itb_ekes-ebeln = itb_ekpo-ebeln
          AND itb_ekes-ebelp > itb_ekpo-ebelp ).
            w_index_ekes = sy-tabix.
            EXIT.
          ENDIF.
        ENDLOOP.
      S'il n'y a pas d'AR alors récupérat° de la date livraison dans EKET.
        LOOP AT itb_eket
                FROM w_index_eket.
          IF  itb_eket-ebeln = itb_ekpo-ebeln
          AND itb_eket-ebelp = itb_ekpo-ebelp.
            IF w_temoin_ar IS INITIAL.
              itb_pca-eindt = itb_eket-eindt.
            ENDIF.
            itb_pca-slfdt = itb_eket-slfdt.
          Calcul du portefeuille fournisseur à partir de la
          qté commandée et la qté reçue
            itb_pca-attdu = itb_pca-attdu + itb_eket-menge -
                            itb_eket-wemng.
          Calcul du montant du poste
            itb_pca-netpr = itb_ekpo-netpr * itb_pca-attdu.
            IF itb_ekpo-peinh NE 0.
              itb_pca-netpr = itb_pca-netpr / itb_ekpo-peinh.
            ENDIF.
          Calcul quantité réceptionnée.
            itb_pca-wemng = itb_pca-wemng + itb_eket-wemng.
          Calcul du retard en nombre de jours calendaires
          Le calcul du retard  ne doit pas prendre en compte
          le jour de livraison
            ADD 1 TO itb_eket-eindt.
            IF NOT itb_pca-attdu  IS INITIAL
            AND    itb_eket-eindt LT sy-datum.
            Calcul du retard en nombre de jours ouvrés
              CLEAR w_retard.
              CALL FUNCTION 'Z_00_BC_WORKDAYS_PER_PERIOD'
                   EXPORTING
                        date_deb = itb_eket-eindt
                        date_fin = sy-datum
                   IMPORTING
                        jours    = w_retard.
              itb_pca-rtard = itb_pca-rtard + w_retard .
            ENDIF.
          ELSEIF itb_eket-ebeln > itb_ekpo-ebeln
          OR (   itb_eket-ebeln = itb_ekpo-ebeln
          AND    itb_eket-ebelp > itb_ekpo-ebelp ).
            w_index_eket = sy-tabix.
            EXIT.
          ENDIF.
        ENDLOOP.
      Recherche de la derniere date de livraison.
        LOOP AT itb_mseg
                FROM w_index_mseg.
          IF  itb_mseg-ebeln = itb_ekpo-ebeln
          AND itb_mseg-ebelp = itb_ekpo-ebelp.
            READ TABLE itb_mkpf
                       WITH KEY mblnr = itb_mseg-mblnr
                                mjahr = itb_mseg-mjahr
                       BINARY SEARCH.
            IF sy-subrc = 0.
              IF itb_mkpf-bldat > itb_pca-bldat.
                itb_pca-bldat = itb_mkpf-bldat.
              ENDIF.
            ENDIF.
          ELSEIF itb_mseg-ebeln > itb_ekpo-ebeln
          OR (   itb_mseg-ebeln = itb_ekpo-ebeln
          AND    itb_mseg-ebelp > itb_ekpo-ebelp ).
            w_index_mseg = sy-tabix.
            EXIT.
          ENDIF.
        ENDLOOP.
        APPEND itb_pca.
        CLEAR itb_pca.
    FAE26446 suppression parag. suivant
         ELSEIF itb_ekpo-ebeln > itb_ekko-ebeln.
           w_index_ekpo = sy-tabix.
           EXIT.
         ENDIF.
       ENDLOOP.
    Fin FAE26446
      ENDLOOP.
    Thanks in advance for all.....

    Hi
    these are the performance tips
    Instead of using nested Select loops it is often better to use subqueries.
    SELECT * FROM SPFLI
      INTO TABLE T_SPFLI
      WHERE CITYFROM = 'FRANKFURT'
        AND CITYTO = 'NEW YORK'.
    SELECT * FROM SFLIGHT AS F
        INTO SFLIGHT_WA
        FOR ALL ENTRIES IN T_SPFLI
        WHERE SEATSOCC < F~SEATSMAX
          AND CARRID = T_SPFLI-CARRID
          AND CONNID = T_SPFLI-CONNID
          AND FLDATE BETWEEN '19990101' AND '19990331'.
    ENDSELECT.
    The above mentioned code can be even more optimized by using subqueries instead of for all entries.
    SELECT * FROM SFLIGHT AS F INTO SFLIGHT_WA
        WHERE SEATSOCC < F~SEATSMAX
          AND EXISTS ( SELECT * FROM SPFLI
                         WHERE CARRID = F~CARRID
                           AND CONNID = F~CONNID
                           AND CITYFROM = 'FRANKFURT'
                           AND CITYTO = 'NEW YORK' )
          AND FLDATE BETWEEN '19990101' AND '19990331'.
    ENDSELECT.
    <b>Internal Tables</b>
    1.     Table operations should be done using explicit work areas rather than via header lines.
    2.     Always try to use binary search instead of linear search. But don’t forget to sort your internal table before that.
    3.     A dynamic key access is slower than a static one, since the key specification must be evaluated at runtime.
    4.     A binary search using secondary index takes considerably less time.
    5.     LOOP ... WHERE is faster than LOOP/CHECK because LOOP ... WHERE evaluates the specified condition internally.
    6.     Modifying selected components using “ MODIFY itab …TRANSPORTING f1 f2.. “ accelerates the task of updating  a line of an internal table.
    Point # 2
    READ TABLE ITAB INTO WA WITH KEY K = 'X‘ BINARY SEARCH.
    IS MUCH FASTER THAN USING
    READ TABLE ITAB INTO WA WITH KEY K = 'X'.
    If TAB has n entries, linear search runs in O( n ) time, whereas binary search takes only O( log2( n ) ).
    Point # 3
    READ TABLE ITAB INTO WA WITH KEY K = 'X'. IS FASTER THAN USING
    READ TABLE ITAB INTO WA WITH KEY (NAME) = 'X'.
    Point # 5
    LOOP AT ITAB INTO WA WHERE K = 'X'.
    ENDLOOP.
    The above code is much faster than using
    LOOP AT ITAB INTO WA.
      CHECK WA-K = 'X'.
    ENDLOOP.
    Point # 6
    WA-DATE = SY-DATUM.
    MODIFY ITAB FROM WA INDEX 1 TRANSPORTING DATE.
    The above code is more optimized as compared to
    WA-DATE = SY-DATUM.
    MODIFY ITAB FROM WA INDEX 1.
    7.     Accessing the table entries directly in a "LOOP ... ASSIGNING ..." accelerates the task of updating a set of lines of an internal table considerably
    8.    If collect semantics is required, it is always better to use to COLLECT rather than READ BINARY and then ADD.
    9.    "APPEND LINES OF itab1 TO itab2" accelerates the task of appending a table to another table considerably as compared to “ LOOP-APPEND-ENDLOOP.”
    10.   “DELETE ADJACENT DUPLICATES“ accelerates the task of deleting duplicate entries considerably as compared to “ READ-LOOP-DELETE-ENDLOOP”.
    11.   "DELETE itab FROM ... TO ..." accelerates the task of deleting a sequence of lines considerably as compared to “  DO -DELETE-ENDDO”.
    Point # 7
    Modifying selected components only makes the program faster as compared to Modifying all lines completely.
    e.g,
    LOOP AT ITAB ASSIGNING <WA>.
      I = SY-TABIX MOD 2.
      IF I = 0.
        <WA>-FLAG = 'X'.
      ENDIF.
    ENDLOOP.
    The above code works faster as compared to
    LOOP AT ITAB INTO WA.
      I = SY-TABIX MOD 2.
      IF I = 0.
        WA-FLAG = 'X'.
        MODIFY ITAB FROM WA.
      ENDIF.
    ENDLOOP.
    Point # 8
    LOOP AT ITAB1 INTO WA1.
      READ TABLE ITAB2 INTO WA2 WITH KEY K = WA1-K BINARY SEARCH.
      IF SY-SUBRC = 0.
        ADD: WA1-VAL1 TO WA2-VAL1,
             WA1-VAL2 TO WA2-VAL2.
        MODIFY ITAB2 FROM WA2 INDEX SY-TABIX TRANSPORTING VAL1 VAL2.
      ELSE.
        INSERT WA1 INTO ITAB2 INDEX SY-TABIX.
      ENDIF.
    ENDLOOP.
    The above code uses BINARY SEARCH for collect semantics. READ BINARY runs in O( log2(n) ) time. The above piece of code can be more optimized by
    LOOP AT ITAB1 INTO WA.
      COLLECT WA INTO ITAB2.
    ENDLOOP.
    SORT ITAB2 BY K.
    COLLECT, however, uses a hash algorithm and is therefore independent
    of the number of entries (i.e. O(1)) .
    Point # 9
    APPEND LINES OF ITAB1 TO ITAB2.
    This is more optimized as compared to
    LOOP AT ITAB1 INTO WA.
      APPEND WA TO ITAB2.
    ENDLOOP.
    Point # 10
    DELETE ADJACENT DUPLICATES FROM ITAB COMPARING K.
    This is much more optimized as compared to
    READ TABLE ITAB INDEX 1 INTO PREV_LINE.
    LOOP AT ITAB FROM 2 INTO WA.
      IF WA = PREV_LINE.
        DELETE ITAB.
      ELSE.
        PREV_LINE = WA.
      ENDIF.
    ENDLOOP.
    Point # 11
    DELETE ITAB FROM 450 TO 550.
    This is much more optimized as compared to
    DO 101 TIMES.
      DELETE ITAB INDEX 450.
    ENDDO.
    12.   Copying internal tables by using “ITAB2[ ] = ITAB1[ ]” as compared to “LOOP-APPEND-ENDLOOP”.
    13.   Specify the sort key as restrictively as possible to run the program faster.
    Point # 12
    ITAB2[] = ITAB1[].
    This is much more optimized as compared to
    REFRESH ITAB2.
    LOOP AT ITAB1 INTO WA.
      APPEND WA TO ITAB2.
    ENDLOOP.
    Point # 13
    “SORT ITAB BY K.” makes the program runs faster as compared to “SORT ITAB.”
    Internal Tables         contd…
    Hashed and Sorted tables
    1.     For single read access hashed tables are more optimized as compared to sorted tables.
    2.      For partial sequential access sorted tables are more optimized as compared to hashed tables
    Hashed And Sorted Tables
    Point # 1
    Consider the following example where HTAB is a hashed table and STAB is a sorted table
    DO 250 TIMES.
      N = 4 * SY-INDEX.
      READ TABLE HTAB INTO WA WITH TABLE KEY K = N.
      IF SY-SUBRC = 0.
      ENDIF.
    ENDDO.
    This runs faster for single read access as compared to the following same code for sorted table
    DO 250 TIMES.
      N = 4 * SY-INDEX.
      READ TABLE STAB INTO WA WITH TABLE KEY K = N.
      IF SY-SUBRC = 0.
      ENDIF.
    ENDDO.
    Point # 2
    Similarly for Partial Sequential access the STAB runs faster as compared to HTAB
    LOOP AT STAB INTO WA WHERE K = SUBKEY.
    ENDLOOP.
    This runs faster as compared to
    LOOP AT HTAB INTO WA WHERE K = SUBKEY.
    ENDLOOP.
    <b>Reward if usefufll</b>

  • Avoid nested loops

    I have an internal table (itab) with a field having vale in the form as shown below;
    0001-0003;0005;0007-0009 (In one row)
    This means it has values  0001 to 0003 0005 0007 to 0009
    I have to compare these values with some other table itab3 which has these values singly means 0001 0002 0003...etc (all in different rows ). so for that I have used nested loops because i need to expand all values to compare with itab3 table something like this :
    loop at itab
        split <itab-field1> at ';' into itab2.
      loop at itab2
         split itab2-field at '-' into var1 var2.
            while var1 le var2.
               append var1 to new table
              increment var1     
           endwhile
      endloop
    endloop
    By this way I get vaues in new table as :
    0001
    0002
    0003
    0005
    0007
    0008
    0009
    So plz tell me is thr some other way by which I can avoid nested loops

    But still it avoids 2 splits
    Yes Rainer, you are right but still my code improves performance.I checked it .
    data:start type i,
         end type i,
         res type i.
    data:begin of itab1 occurs 0,
         str type char255,
         end of itab1.
    data:begin of itab2 occurs 0,
         str type char255,
         end of itab2.
    data:var1 type char04,
         var2 type char04.
    get RUN TIME FIELD start.
    itab1-str = '0001-0003;0005;0007-0009'.
    append itab1.
    loop at itab1.
        split itab1-str at ';' into table itab2.
      loop at itab2.
         split itab2-str at '-' into var1 var2.
            while var1 le var2.
               var1 = var1 + 1.
           endwhile.
      endloop.
    endloop.
    get RUN TIME FIELD end.
    res = end - start.
    write :'code1-', res.
    skip 1.
    DATA:lv_str1 TYPE char255,
         lv_low(04) TYPE n,
         lv_high(04) TYPE n.
    TYPES:BEGIN OF ty_itab,
          line TYPE char255,
          END OF ty_itab.
    DATA:itab TYPE TABLE OF ty_itab,
         wa TYPE ty_itab.
    clear:start,end,res.
    get RUN TIME FIELD start.
    wa-line = '0001-0003;0005;0007-0009'.
    APPEND wa TO itab.
    LOOP AT itab INTO wa.
      DO.
        IF wa-line CA ';'.
          lv_str1 = wa-line+0(sy-fdpos).
          sy-fdpos = sy-fdpos + 1.
          wa-line+0(sy-fdpos) = ' '.
          CONDENSE wa-line.
          IF lv_str1 CA '-'.
            lv_low = lv_str1+0(sy-fdpos).
            lv_high = lv_str1+sy-fdpos(*).
            WHILE NOT lv_low GT lv_high.
               ADD 1 TO lv_low.
            ENDWHILE.
          ELSE.
          ENDIF.
        ELSE.
          IF wa-line CA '-'.
            lv_low = wa-line+0(sy-fdpos).
            lv_high = wa-line+sy-fdpos(*).
            WHILE NOT lv_low GT lv_high.
              ADD 1 TO lv_low.
            ENDWHILE.
          ELSE.
          ENDIF.
          EXIT.
        ENDIF.
      ENDDO.
    ENDLOOP.
    skip 1.
    get RUN TIME FIELD end.
    res = end - start.
    write: 'code2-',res.
    Edited by: Keshav.T on Jun 18, 2010 5:24 PM
    Edited by: Keshav.T on Jun 18, 2010 5:25 PM

  • Nested Loops...

    I'm not sure if this is the best place to ask this, but I am writing rather complex queries here, and often times I find that the "NESTED LOOP"s of all varying types are quite deceptive in their 'cost' in the Plan Explanation for these queries.
    As well, they often take quite a bit longer. (whatever reasons anyone has to refute this, please don't. They may have their place in database architecture, but for my purposes just assume I am infallible when i say they are slower).
    Now, I have tried putting in the USE_HASH() hint, i've tried using the NO_USE_NL() hint, and no matter what I do, every time i load the Explain Plan window, there is a (many) confounded Nested Loop(s) in plan where none should exist at all.
    HOw can i globally put something in there that says "Hey Oracle! Don't use nested loops for this query!"
    1 select /* +NO_USE_NL(table4 t1, t2, t3) */    
    : /* +USE_HASH(table4 t1, t2, t3) */    
    2 t1.ID_no, t1.t2ID_no, t1.itemdata, table4.ID
    3 from (
    4 (
    5 table1 t1 inner join table2 t2
    6 on (t1.t2ID_no = t2.ID_no)
    7 inner join table3 t3
    8 on (t3.owner_no = h.household_no)
    9 ) left join table4
    0 on (t1.ID_no = table4.t1ID_no)
    Now, I don't use BOTH hints at the same time, i just wanted you to see my formatting and how I usually use this. NOw between t1, t2, and t3, the plan depicts all HASH joins, however, between them and Table4, I am getting a NESTED LOOPS OUTER. Why won't it recognize the hint i've put in there to tell it to stop u sing nested loops for the entire query?
    Thanks
    Jaeden "Sifo Dyas" al'Raec Ruiner

    Sorry about the whole infallible thing, but a lot of times i want a question answered, and on many development sites I get a lot of descriptions on how "this works better this way" or "the system is supposed to do this" or something, and they don't answer my question.
    I know that nested loops are useful in many circumstances, and I wanted to avoid having someone comment "well the nested loop is faster for this, and this and this" when my question was how to eliminate them, not "why" i wanted to eliminate them. chuckel
    Anyway. Thanks for the indication about the format of the hints. I guess I mis-read sometime in someone else's script here, cause I thought the + was next to the hint, not next to the *. That woudl explain a lot.
    As for the commas, what's that about? Are commas necessary or superfluous to the listing of the tables in the hint?
    Thanks
    Jaeden "Sifo Dyas" al'Raec Ruiner

  • @@FETCH_STATUS in nested loops

    Does fetch status in nested loops conflict?
    I have a script that should output a cluster record line and for each cluster record it must create a line for each household in the cluster.  All the data is pulled from one table, 'LFS_APRIL_2015.dbo.LISTING'.
    This is the script:
    --VARIABLE DECLARATION
    DECLARE @CLUSTER FLOAT, @HOUSEHOLD_NUMBER FLOAT, @FULL_ADDRESS CHAR(50), @HEAD_NAME CHAR(24)--CLUSTER LOOP
    DECLARE CLUSTER_CURSOR CURSOR FOR
    SELECT [LFS_APRIL_2015].[dbo].[LISTING].CLUSTER
    from [LFS_APRIL_2015].[dbo].[LISTING] where CLUSTER IS NOT NULL and DISTRICT = 1
    OPEN CLUSTER_CURSOR
    FETCH NEXT FROM CLUSTER_CURSOR INTO @CLUSTER
    WHILE @@FETCH_STATUS = 0
    BEGIN--OUTPUT THE CLUSTER RECORD
    PRINT STR(@CLUSTER,3) + STR(1,1) + STR(24,3)
    --HOUSEHOLD LOOP
    DECLARE HOUSEHOLD_CURSOR CURSOR FOR
    SELECT [LFS_APRIL_2015].[dbo].[LISTING].HOUSEHOLD_NUMBER, FULL_ADDRESS, HEAD__INSTITUTION__BUSINESS_NAME
    from [LFS_APRIL_2015].[dbo].[LISTING] where CLUSTER IS NOT NULL AND IS_HOUSEHOLD = 1 AND CLUSTER = @CLUSTER
    OPEN HOUSEHOLD_CURSOR
    FETCH NEXT FROM HOUSEHOLD_CURSOR INTO @HOUSEHOLD_NUMBER, @FULL_ADDRESS, @HEAD_NAME
    WHILE @@FETCH_STATUS = 0
    BEGIN
    --OUTPUT THE HOUSEHOLDS IN THE CLUSTER
    PRINT right('000'+cast(@CLUSTER as varchar(10)),3) + STR(2,1) + STR(@HOUSEHOLD_NUMBER,2) + @FULL_ADDRESS + @HEAD_NAME + '000' + ' ' + STR(0,1)
    FETCH NEXT FROM HOUSEHOLD_CURSOR INTO @HOUSEHOLD_NUMBER, @FULL_ADDRESS, @HEAD_NAME
    END
    CLOSE HOUSEHOLD_CURSOR
    DEALLOCATE HOUSEHOLD_CURSOR
    FETCH NEXT FROM CLUSTER_CURSOR INTO @CLUSTER
    END
    CLOSE CLUSTER_CURSOR
    DEALLOCATE CLUSTER_CURSOR
    It appears however that the clusters are being repeated.
    Where have I gone wrong!

    >> I have a script that should output a cluster record [sic] [sic] line and for each cluster record [sic] it must create a line for each household in the cluster. All the data is pulled from one table, 'LFS_APRIL_2015.dbo.LISTING'.<<
    Please follow the basic Netiquette of all SQL forums. Post DDL that follows ISO-11179 rules for data element names. Use ISO-8601 formats for temporal data. Use induSTRy standard encodings (ISBN, UPC, GTIN, etc) and avoid needless dialect. Give clear specifications.
    Give sample data.
    If you do not know that rows are not records, fields are not columns and tables are not files, then you should not be posting. SQL is a declarative language, so we hate cursors. We hate local variables, too. 
    Using upper case letters is a code smell that says your mindset is still in punch cards and sequential processing. And finally you used a date in a data STRuctured name! Back in the 1960's, this is how we named magnetic tapes. In RDBMS, we name tables for the
    set of entities they model. 
    Why are you using FLOAT? Is there really household number like 3.141592653 in your data model? But if it is really an integer, you still screwed up. What math do you do with it? 
    The USPS standards use 5 lines of VARCHAR(35) for a Street address. But you pack all of that in CHAR(50). Think about how vague “cluster” is – Size? Name? Location? WHAT?? 
    The purpose of PRINT in T-SQL is debugging and not output. The purpose of SQL is to handle the data, not to format and display data, like you are doing. Learn what a “presentation layer” in RDBMS is. 
    Follow the rules, and post that DDL, then we will try to help you. All you can get is a stinking kludge with this posting. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Need help with nested loop (c:forEach) tags. Can I break from inner loop?

    Hi all, I have this annoying problem and I am looking for any suggestions.
    I have 2 select boxes. One is for all available users, and second - for selected users (designated as admins). The list of all users is available in a collection (2 properties userId and userName displayed in the code below). The list of admins contains only userId (as strings).
    I have no problem with populating selected users (admins) list, reusing pretty much the same logic below, but I cannot find a way to break out from the nested loop once the match is found, to avoid repetitions leading to incorrect display of results.
    <select name=available>
    <c:forEach items="${users}" var="user" varStatus="outer">
        <c:forEach items="${adminIds}" var="adminId" varStatus="inner">
            <c:if test="${user.userId!=adminId">
                 <option value="<c:out value="${user.userId}" />"><c:out value="${user.userFullName}"/></option>
            </c:if>
        </c:forEach>
    </c:forEach>
    </select>
    <select name=selected>
    <c:forEach items="${users}" var="user" varStatus="outer">
        <c:forEach items="${adminIds}" var="adminId" varStatus="inner">
            <c:if test="${user.userId==adminId">
                 <option value="<c:out value="${user.userId}" />"><c:out value="${user.userFullName}"/></option>
            </c:if>
        </c:forEach>
    </c:forEach>
    </select>Can anyone help, please? I am also restricted to JSP 1.2

    Double post: http://forum.java.sun.com/thread.jspa?threadID=707950&tstart=0

  • 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

  • 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

  • Creating nested loops

    Hi!
    I would like to list all Combinations of a list A and a list B (each containing 5 integers) in a third list C in order to get 25 combinations. I am intending to use nested loops so that on the first loop the second loop starts and then the result lets say list A + list B are listed in the list C. Is there any other way of doing this with Labview or I am on the right track?
    Best Regards,
    Hamid  

    You can use the polymorphic array math to accomplish this.  Inside of a single for loop, index Array A and add that to the entire Array B in one shot.  At this point, there are numerous ways to take the output.  Probably the simpliest is to reshape the output 2D array into a 1D array.  For better memory allocation, you can preinitialize a 1D array and replace elements in the for loop but in the end it accomplishes the same task.  See attached example (LV7.1.1).  Of course everything is dependant on what you are going to do with this, what operations, when and where the numbers come from.
    Paul
    Paul <--Always Learning!!!
    sense and simplicity.
    Browse my sample VIs?
    Attachments:
    arrayMath.vi ‏33 KB

  • XML nested Loop?

    hi all.
    I´ve just completed a little test for making a tree
    component with custom
    icons / bransch.
    However, i can only get my first branch to show custom
    icons.(links -
    document) I figure I need to make a nested loop to Iterate
    over
    nextSibling?. I tried ALOT, but i guess I´m doing
    something completely
    wrong.
    here is code for my tree so far:
    my_xml = new XML();
    my_xml.ignoreWhite = true;
    my_xml.load("tree.xml");
    my_xml.onLoad = function(){
    myTree.dataProvider = this.firstChild;
    var folders = my_xml.firstChild.firstChild;
    var docs = folders.childNodes;
    for (var i=0; i < docs.length; i++){
    currDoc = docs
    trace(docs);
    var docIcon = currDoc.attributes.pic;
    switch(docIcon){
    case "pdf":
    myTree.setIcon(currDoc, "pdfIcon");
    break;
    case "word":
    myTree.setIcon(currDoc, "wordIcon");
    break;
    case "excel":
    myTree.setIcon(currDoc, "excelIcon");
    break;
    case "ie":
    myTree.setIcon(currDoc, "ieIcon");
    break;
    }//switch
    } //for
    };//onLoad
    And here is the XML I used:
    <node label="» Dokument typer">
    <node label="» links - document">
    <node label="test.url" url="
    http://www." pic="ie" info="test text" />
    <node label="test.doc" url="test.doc" pic="word"
    info="test text" />
    <node label="test.excel" url="test.xls" pic="excel"
    info="test text" />
    <node label="test.pdf" url="test.pdf" pic="pdf"
    info="test text." />
    </node>
    <node label="» Links - document">
    <node label="test URL" url="
    http://www." pic="ie" info="test text."
    />
    <node label="test URL" url="
    http://www." pic="ie" info="test text."
    />
    </node>
    </node>

    Solved it ..works nicely :D
    ty anyways.
    //cleaner
    "cLeAnEr" <[email protected]> skrev i meddelandet
    news:ekm1vc$r8h$[email protected]..
    > hi all.
    >
    > I´ve just completed a little test for making a tree
    component with custom
    > icons / bransch.
    > However, i can only get my first branch to show custom
    icons.(links -
    > document) I figure I need to make a nested loop to
    Iterate over
    > nextSibling?. I tried ALOT, but i guess I´m doing
    something completely
    > wrong.
    >
    >
    > here is code for my tree so far:
    >
    > my_xml = new XML();
    > my_xml.ignoreWhite = true;
    > my_xml.load("tree.xml");
    >
    > my_xml.onLoad = function(){
    > myTree.dataProvider = this.firstChild;
    >
    >
    > var folders = my_xml.firstChild.firstChild;
    > var docs = folders.childNodes;
    >
    > for (var i=0; i < docs.length; i++){
    > currDoc = docs
    > trace(docs);
    >
    > var docIcon = currDoc.attributes.pic;
    >
    > switch(docIcon){
    > case "pdf":
    > myTree.setIcon(currDoc, "pdfIcon");
    > break;
    > case "word":
    > myTree.setIcon(currDoc, "wordIcon");
    > break;
    > case "excel":
    > myTree.setIcon(currDoc, "excelIcon");
    > break;
    > case "ie":
    > myTree.setIcon(currDoc, "ieIcon");
    > break;
    > }//switch
    > } //for
    > };//onLoad
    >
    >
    > And here is the XML I used:
    >
    > <node label="» Dokument typer">
    > <node label="» links - document">
    > <node label="test.url" url="
    http://www." pic="ie" info="test text" />
    > <node label="test.doc" url="test.doc" pic="word"
    info="test text" />
    > <node label="test.excel" url="test.xls" pic="excel"
    info="test text" />
    > <node label="test.pdf" url="test.pdf" pic="pdf"
    info="test text." />
    > </node>
    > <node label="» Links - document">
    > <node label="test URL" url="
    http://www." pic="ie" info="test text."
    />
    > <node label="test URL" url="
    http://www." pic="ie" info="test text."
    />
    > </node>
    > </node>
    >

  • 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 vs nested loop

    DECLARE @tableA table (Productid varchar(20),Product varchar(20),RateID int)
    insert into @tableA values('1','Mobile',2);
    insert into @tableA values('2','Chargers',4);
    insert into @tableA values('3','Stand',6);
    insert into @tableA values('4','Adapter',8);
    insert into @tableA values('5','Cover',10);
    insert into @tableA values('6','Protector',12);
    --SELECT * FROM @tableA
    DECLARE @tableB table (id varchar(20),RateID int,Rate int)
    insert into @tableB values('1',2,200);
    insert into @tableB values('2',4,40);
    insert into @tableB values('3',6,60);
    insert into @tableB values('4',8,80);
    insert into @tableB values('5',10,10);
    insert into @tableB values('6',12,15);
    --SELECT * FROM @tableB
    SELECT Product,Rate
    FROM @tableA a
    JOIN @tableB b ON a.RateID = b.RateID
    Above is the sample query, where in execution plan it shows the Hash Match (inner Join). Now how do I change it to Nested Loop with out changing the query? help plz

    Is Hash Match(inner join) or Nested loop is better to have in the query?
    That depends on the size of the tables, available indexes etc. The optimizer will (hopefully) make the best choice.
    Above is the sample query, where in execution plan it shows the Hash Match (inner Join). Now how do I change it to Nested Loop with out changing the query?
    The answer that you should leave that to the optimizer in most cases.
    I see that the logical read for nested loop is higher than Hash Match.
    But Hash Match tends to need more CPU. The best way to two compare two queries or plans is wallclock time.
    On a big tables, how do we reduce the logical read? 
    Make sure that there are usable indexes.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • 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