Logic for nested loops

Hi guy's,
I required tipical logic pls any body help me,
I have to fethch EBELN ,BEDAT from EKKO and  MATNR from EKPO
based on that i have to go KEKO table based on MATNR
I have to fetch KALNR and KADKY ,  BEDAT should be between range of BIDAT and KADAT.
Based on KALNR   i have to go for CKIS table now i fetch  COMPONENT MATERIALS and ELEMT
If i get the ELEMT 000 again i have to take COM.MATNR  again we have to go KEKO I have to get take KALNR KADKY and
again i have to go for CKIS .
I have to continue this logic up to in ELEMT = 010 .Here iam geting the problem.
MATNR   ELEMT        I have to continue this loop up to elemt become 010 . how many tables i have to declared how to read
A             000                the tabel.Pls any body help me.
B              010
C              010
D              000
Thanks
santhosh
Edited by: santhosh kumar on Sep 2, 2009 10:13 PM

Hi,
You have all the tables and field names and the link between each of the tables. Why dont you start with the select query as per the requirement? You can always revert back if you are stuck up anywhere. Generic questions are not allowed here.
Regards,
Vikranth

Similar Messages

  • Alternative for nested loops

    Hi Gurus,
    I have the following problem :
    There are 2 internal tables namely 1 &2.
    Now there is a field in table 1 'AUGBL' which should be equal to  field in Table2-BELNR.
    Now if there is a match between TABLE1-AUGBL and TABLE2-BELNR,
    so we move to table 2 to look for 'augbl' associated with 'belnr' in the same table.
    Then I have to give the following logic -
    If table2-belnr = table2-augbr,
       Then do nothing.
    Else.
    Check, for the Augbl which will equal Belnr in a different position in table 2.
    For ex:
    Table1-AUGBL = 2.
    So now we have to search a field when Table1-augbl = Table2-belnr = 2.
    Now for this record in table2, there are 2 conditions:
    When Table2-augbl = 2, (in which case we do nothing)
    or,
    Table2-augbl NE 2, or Table2-augbl = 3.
    In the latter case,  there will be another field in Table2-BELNR = 3. So we go to this record now and check for the associated AUGBL and do the same checks above.
    We keep on continuing for this till the time we do not get the Table2-belnr = Table2-augbl in the end for the same record.
    Now I want to achieve this without using nested loop.
    Kindly help as I already have wated a lot of time.
    Please let me know if there are any clarifications.

    Hey..
    Before u get the data into two internal tables through SELECT stmts.
    U can use JOIN instead of two SELECT stmts ..that wud fetch the data into single internal table..
    and that may ease ur validations and further process..
    try this out..
    Thanks and Regards,
    KC

  • Wrong code analysis on "unreachable statement" for nested loops

    Try this with JavaFX 1.2 (NetBeans 6.5.1)
    function foo():Void {
        for (i in [0..<10]) {
            for (j in [0..<10]) { // be marked as unreachable statement
                if (match()) {
                    break;
                return; // I just want to get out
            // break goes here
    }It shows "unreachable statement" at the second 'for'.
    Right now I just change "return;" to "if (true) return;" to get it pass.

    I agree it is a bug at the compiler level. If I do your change and add println of i and j, I get a trace on j, obviously.
    You should file a bug report at [Jira / Kenai|http://javafx-jira.kenai.com/] (or I can do if you don't want to create an account).
    [EDIT] Uh, no, it is a known problem: [Bogus 'Unreachable statement' error|http://javafx-jira.kenai.com/browse/JFXC-3323], I will add this thread as a comment.
    A more complete use case:
    function foo(): Void {
         for (i in [ 0 ..< 5 ]) {
              println("I {i}");
              for (j in [ 0 ..< 5 ]) {
                   println("J {j}");
                   if (match()) {
                        break;
                   println("Some operation in the inner loop");
                   if (true) return;
              // break goes here
    function match(): Boolean { return Math.random() > 0.5; }
    foo();Now, the inner loop isn't really necessary, we never go beyond 0 for j... But technically, there is no unreachable statement, unless it means we never go up to 5 in the inner loop. In this case, Robert Field is right, the error message should be clearer.
    Edited by: PhiLho on 29 juil. 2009 10:17

  • 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]

  • Is merge join cartesian more cpu intensibe than nested loop ?

    Hi,
    just wonderning which access method is more cpu intensive , lets supposed we got 2 the same row sources and doing joing via merge join cartesian and next case is nested loop .
    I know NL can be cpu intensive because of tight loop access , but what abour MJC ?
    I can see bufferd sort but not sure is that cpu friendly ?
    Regards
    GregG

    Hi,
    I think in your case it's more accurate to compare a NESTED LOOP (NL) to a MERGE JOIN (MJ), because CARTESIAN MERGE JOIN is a rather special case of MJ.
    Merge join sorts its inputs before combining them, and it could be efficient when one or both of inputs are already sorted.
    Regarding your question (which is more CPU intensive):
    1) if MERGE JOIN involves disk spills, then CPU is probably irrelevant, because disk operations are much more expensive
    2) the amount of work to combine rowsources via a MJ depends on how well they are aligned with respect to each other, so I don't think it can be expressed via a simple formula.
    For nested loops, the situation is much more simple: you don't need to do any special work do combine the rowsource, so the cost is just the sum of the cost acquiring the outer rowsource plus the number of iterations times the cost of one iteration. If the data is read from disk, then CPU probably won't matter much, if most of reads are logical ones than CPU becomes of a factor (it's hard to tell how much work CPU will have to do per one logical read because there are two many factors here -- how many columns are accessed, how they are located within the block, are there any expensive math functions applied to any of them etc.)
    Best regards,
    Nikolay

  • NESTED LOOP or SORT MERGE

    Hi All,
    How can we judge which one is best to use for the query- NESTED LOOP
    - SORT MERGE
    - HASH JOINThanx.. Ratan

    Hi...
    For Nested Loop Joins:
    Nested loop joins are useful when small subsets of data are being joined and if the join condition is an efficient way of accessing the second table.
    It is very important to ensure that the inner table is driven from (dependent on) the outer table. If the inner table's access path is independent of the outer table, then the same rows are retrieved for every iteration of the outer loop, degrading performance considerably. In such cases, hash joins joining the two independent row sources perform better.
    For Hash Join:
    Hash joins are used for joining large data sets. The optimizer uses the smaller of two tables or data sources to build a hash table on the join key in memory. It then scans the larger table, probing the hash table to find the joined rows.
    For Sort Merge Joins:
    Sort merge joins can be used to join rows from two independent sources. Hash joins generally perform better than sort merge joins. On the other hand, sort merge joins can perform better than hash joins if both of the following conditions exist:
    The row sources are sorted already.
    A sort operation does not have to be done.
    However, if a sort merge join involves choosing a slower access method (an index scan as opposed to a full table scan), then the benefit of using a sort merge might be lost.
    Sort merge joins are useful when the join condition between two tables is an inequality condition (but not a nonequality) like <, <=, >, or >=. Sort merge joins perform better than nested loop joins for large data sets. You cannot use hash joins unless there is an equality condition.
    In a merge join, there is no concept of a driving table. The join consists of two steps:
    Sort join operation: Both the inputs are sorted on the join key.
    Merge join operation: The sorted lists are merged together.
    If the input is already sorted by the join column, then a sort join operation is not performed for that row source.

  • Nested FOR cursor LOOPs, BASIC QUESTION

    Hello,
    I am trying to nest a For-loop using a cursor (see below), but the program is not entering the second (nested) for-loop. This program compiles fine, but during run-time, the nested loop does not execute. I'd rather not use FETCH statements and keep everything in place. I think the solution is rather trivial, but I'm new to PL/SQL. PLEASE HELP!!!!!
    cursor c1 is
    select coi_con_uid,coi_not_code,coi_closed_yn,coi_timestamp
    from s_coi_con_issue
    where coi_not_code = 'NOT107'
    and coi_timestamp <= v_aweekago
    and coi_closed_yn = 'N';
    cursor c2 is
         select tsk_uid
         from s_tsk_task
         where tsk_status in ('C')
         and tsk_tty_code = 'CONTAC'
         and tsk_date_end = '' FOR UPDATE;     
    BEGIN
    select to_date(sysdate - 7) into v_aweekago from dual;
    DBMS_OUTPUT.PUT_LINE('System date used is ' || v_aweekago);
    FOR coi_row in c1 LOOP
    v_tsk_cnt := 0;
    v_coi_row_cnt := v_coi_row_cnt + 1;
    v_con_uid := rtrim(to_char(coi_row.coi_con_uid));
    v_tsk_act_str := ('"CON_UID","' || v_con_uid || '"') ;
    DBMS_OUTPUT.PUT_LINE('COI_CON_UID: ' || v_con_uid);
    DBMS_OUTPUT.PUT_LINE('v_tsk_act_str: ' || v_tsk_act_str);
    -----The Program is not entering into this Loop
              FOR tsk_row in c2 LOOP
              v_update_cnt := v_update_cnt + 1;
                   update s_tsk_task
                   set tsk_status = 'A'
                   where tsk_uid = tsk_row.tsk_uid and
                   tsk_action_string = v_tsk_act_str;     
                   DBMS_OUTPUT.PUT_LINE('----Task updated');                         
              END LOOP;
    END LOOP;
    COMMIT;

    using your query on your cursor c2 when you execute it on sql*plus did it return any rows?
      select tsk_uid
        from s_tsk_task
       where tsk_status in ('C')
         and tsk_tty_code = 'CONTAC'
         and tsk_date_end = ''; if not it might have something to do with the predicates in your where clause
         and tsk_date_end = '';consider revising your c2 cursor select statement to something like:
    cursor c2 is
      select tsk_uid
        from s_tsk_task
       where tsk_status   = 'C'
         and tsk_tty_code = 'CONTAC'
         and tsk_date_end IS NULL
      FOR UPDATE;

  • Creating new 'category/index' for apple loops in logic

    As well as the standard apple loops, I currently have an additional apple loops jampack & a number of self-made apple loops.
    These have been indexed automatically, & can be referenced via the drop-down on the top right of the loop browser as 'jampack' & 'my loops' respectively.
    I've just bought a 3rd party dvd of apple loops, & would like to be able to reference these via the same kind of category in the loopbrowser drop down, however, the 3rd party DVD has no 'installer' like the official jampack, but instead just has folders of 'apple-loopyfied' AIFFs to drop in the loop browser.
    I assume if this is the case they will appear by default under 'my loops', which isn't ideal - is there a way I can manually create another category(/folder?) for these loops which I can reference via Logic's loop browser drop-down?
    Any help appreciated
    Adam

    ok, still stuck on this but have found the following from page 61 on 'new in logic 7.2'
    http://manuals.info.apple.com/en/NewFeatures_in_Logic_Pro7.2.pdf
    'To keep things tidy, the loop browser offers advanced loop management tools, the jam pack management drop-down allows you to limit the display to loops from a specific jam pack, or other folder' .....then....describing an option from the pull-down, 'vendor x - choose to play loops from a specific third party vendor'
    - this looks perfect for what i want to do, but i assume a vendor must include certain data/meta-data in their loops for this indexing to work & display under vendor x as a dropdown, how do i know if the dvd I have bought will have this? hmmmm....

  • Nested table updation in FOR Cursor loop

    Hello,
    I have nested table as follows:
    SQL> desc fp
    Name Null? Type
    ORDER_NUM NOT NULL VARCHAR2(10)
    ORDER_TIE_NUM NOT NULL VARCHAR2(10)
    FACILITY NOT NULL VARCHAR2(10)
    ON_SHORTS NUMBER(2)
    ACTIVE_SHORTS NUMBER(2)
    PARTS DPM_TRANSFORM_CODE.FP_SLC_SHORT
    FIRST_SHORT DATE
    LAST_SHORT DATE
    SQL> desc DPM_TRANSFORM_CODE.FP_SLC_SHort
    DPM_TRANSFORM_CODE.FP_SLC_SHort TABLE OF DPM_TRANSFORM_CODE.FP_SHORT_INFO
    Name Null? Type
    PART_NUM VARCHAR2(7)
    AREA VARCHAR2(7)
    PART_QTY NUMBER(3)
    ON_SHORT_CNT NUMBER(4)
    OFF_SHORT_CNT NUMBER(4)
    FIRST_DATE DATE
    LAST_DATE DATE
    UPDATE TABLE(SELECT PARTS FROM DPM_REPORTING.FP WHERE ORDER_NUM = P.ORDER_NUM AND ORDER_TIE_NUM = P.ORDER_TIE_NUM) PARTS
    SET PARTS.OFF_SHORT_CNT = PARTS.OFF_SHORT_CNT + 1
    WHERE PARTS.last_date < SYSDATE - 2/24;
    This Update Statement is in FOR Cursor Loop
    where select statement for the cursor is
    "SELECT ORDER_NUM,ORDER_TIE_NUM,PARTS FROM DPM_REPORTING.FP WHERE FACILITY = 'PN1'"
    This select statement generates 20000 records & due to which the Update statement gets executed that many times inside FOR loop.The Procedure has become quite slow due to this.
    Please help.
    Thanks,
    Rekha

    You could do it all in one sql update statement, without any pl/sql or cursor or looping:
    UPDATE fp t1
    SET    t1.parts =
           CAST (MULTISET (SELECT part_num, area, part_qty, on_short_cnt,  
                                  CASE WHEN last_date < SYSDATE - 2/24
                                       THEN off_short_cnt + 1
                                       ELSE off_short_cnt
                                  END,  
                                  first_date, last_date
                           FROM   TABLE (SELECT parts
                                         FROM   fp
                                         WHERE  facility = 'PN1'
                                         AND    order_num = t1.order_num
                                         AND    order_tie_num = t1.order_tie_num))    
                 AS fp_slc_short)
    WHERE  t1.facility = 'PN1'
    /

  • 106 nested for next loops!

    Well, this is not a problem, but I just had to mention that I could not believe that Java would actually process 106 nested for next loops. I had an hour of free time yesterday and we needed to run an exhaustive branch test of an application that we have, to do so we needed to have 104 data elements generated with all possible cases. I thought, what the heck, and tried it in Java--our old language wouldn't do that on it's best day and in our dreams! Java did it, it not only did it, but it left a clean environment after it was done!

    well, here is more the thing that comes to mind with i think about loop limits: in VB when you get a dozen or so pending closing parentesis, things start to go funny in memory and in some cases, the formula/routine becomes too complicated to interpret. Just how many pending closing parentesis will be accepted before things go bonkers.

  • Need to access parent elements in nested for-each loop

    Hi All,
    I have a xslt mapping requirement in which I am completely stuck. The details are as listed below. Please help!
    Schema structure is as follows:
    Root
    Payload
    Transaction-123
    Loop-LINE
    Loop-SDPP
    Segment-FSTT
    Element-111
    Required xslt file structure is:
    <xsl:for-each Loop-LINE>
    <tns:Item>
    <Line-1000>
    <Line-2000>
    <Line-3000>
    <Line-8000>
    <xsl:for-each Loop-SDPP>
    <xsl:for-each Segment-FSTT[ns0:Element-111 != "A"]>
    <SDetails>
    </SDetails>
    <xsl:for-each Loop-LINE> --------- How to access Loop-LINE element from this for loop????
    <tns:Item>
    <2000>
    <2020>
    <2070>
    <2150>
    </tns:Item>
    </xsl:for-each>
    </for-each>
    </for-each>
    </tns:item>
    </for-each>
    Need help in understanding how can I run a for-each loop for Loop-LINE which is two levels up in the schema tree structure.
    Thanks..

    Thanks for this answer but I can't obtain the right output with my test case; the multi column must be in the loop as that :
    ALPHABETICAL INDEX C1
    Alternator .......................................... Feed Pump
    Belt Details / Engine Gaskets Sets ..... Flywheel Housing
    < NEW PAGE>
    INDEX ALPHABETIQUE C2
    Alternateur......................................... Culbuteurs
    Bloc-Cylindres.................................... Demarreur
    Denis

  • 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.

  • 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>

  • 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

  • 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

Maybe you are looking for

  • Unstable Apple Web Site

    We members save Apple several thousands of dollars each day in terms of man hours by resolving hundreds of issues that would otherwise be handled by Apple Tech Support. The very least that Apple could do is to provide a more stable web site for us to

  • Low image resolution makes photos blurry ...

    What ever happened to the hi-res image sync feature in iTunes? I remember that there used to be an option to sync full-size images, now I just noticed that all my images recently got "downgraded" to a rather small size, so any zooming in makes them w

  • How to select subtitle tracks?

    I have a project with 10 subtitle tracks. Now, How do I set this up so viewers can choose which language they want? I was thinking I would create a menu that would have buttons to select, but if I right click a button to target, there is no option to

  • Grid within a grid

    Hi, I am new to awt. I am trying to create a series of grids within a grid. The first grid will have three rows and one column. Each of the rows will contain a grid of varying numbers of rows and columns. Has anyone an example of how I would do somet

  • Blank tabs show up on startup

    In Firefox 14, when I start Firefox, two tabs show up: the home page, and a blank tab that can never close (even if I navigate to a different page in that tab, I can never close it). My homepage settings are set to only show the home page, not two ta