Using Looping statements to loop images

Hi Guys i posted a similar question to this before but i couldn't get anywhere using the method that was described to me. Im currently creating a Puyo Puyo game and im nearly done ive been working on this for about 2 months im still new to java. Anyway my question is, is that after my first two puyo images reach the bottom how would i go about having my next images load and then drop and then have that loop. I understand how to create a loop statement but i just don't understand what parameters i would need to put into it and what kind of loop statement i would need i.e. for loop, do loop etc... I really could use some help ive tried and gotten this far but im pretty stuck. I appreciate any help you can provide. Here is my code so far
public class Puyo {
    public int x, y, color;
    public Puyo(int c, int x2, int y2) {
        color = c;
        x = x2;
        y = y2;
import javax.swing.*;
import java.awt.*; 
public class DemoTest extends JPanel {
    public static void main(String[] args) { {
    JFrame frame = new JFrame("Puyo Puyo");
    frame.setContentPane(new PuyoAnimation()); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setSize(200,453);
    frame.setResizable(false);
    frame.setVisible(true);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*; 
import javax.swing.event.*;
import java.util.Random;
public class PuyoLogic extends JPanel {
   public static final int puyoEmpty=0;
  final int board_height = 12;
  final int board_width = 6;
  final int image_height= 32;
  final int image_width = 32;
  final int MAX_X = board_width*image_width;
  final int MAX_Y = board_height*image_height;
  private static final int DELTA_Y = 2;
  private static final int TIMER_DELAY = 20;
  Image images[];
  Puyo puyolist[][];
  Puyo current[];
  Puyo droppingBalls[];
  Timer pptimer;
  Random myRand= new Random();
  boolean keyRight,keyLeft,keyUp;
     public PuyoLogic() {
     super();
        puyolist = new Puyo[board_width][board_height];
        current = new Puyo[2];
        current[0] = new Puyo(myRand.nextInt(4), (board_width * image_width /2), 0);
        current[1] = new Puyo(myRand.nextInt(4), (board_width * image_width /2)+image_width, 0);
    // current[2] = new Puyo(myRand.nextInt(4), (board_width * image_width /2), 0);
   //     current[3] = new Puyo(myRand.nextInt(4), (board_width * image_width /2)+image_width, 0);
     images = new Image[4];
     images[0] = Toolkit.getDefaultToolkit().getImage("puyo_yellow.png");
     images[1] = Toolkit.getDefaultToolkit().getImage("puyo_blue.png");
     images[2] = Toolkit.getDefaultToolkit().getImage("puyo_green.png");
     images[3] = Toolkit.getDefaultToolkit().getImage("puyo_red.png");
     setFocusable(true);
     PuyoMove puyo_move = new PuyoMove(); // Make a new video game KeyListener
     addKeyListener(puyo_move);
     setBackground(Color.BLACK);
      pptimer = new Timer(TIMER_DELAY, new TimerAction());
      pptimer.start();
     public void setAnimation(boolean OnandOff){
        if (OnandOff) {
            pptimer.start(); 
        } else {
            pptimer.stop(); 
    public void NewBlock() {
    int newblock;
    int i,j;
    for(i=0; i<4; i++)
        for(j=0; j<4; j++)
        //puyolist[i][j] = new Puyo[2];
    current[0].x=board_width/2-2;
    current[0].y=0;
    public void puyoBoundsRight(Puyo[] current){
    if ((current[0].x + image_width <= MAX_X - image_width) && (current[1].x + image_width <= MAX_X - image_width)){
    current[0].x += image_width;
    current[1].x += image_width;
    public void puyoBoundsLeft(Puyo[] current){
    if ((current[0].x - image_width >= 0) && (current[1].x - image_width >= 0)){
    current[0].x -= image_width;
    current[1].x -= image_width;
   private class PuyoMove implements KeyListener {
     public void keyTyped(KeyEvent k){}
     public void keyReleased(KeyEvent k){}
     public void keyPressed(KeyEvent k){
        switch (k.getKeyCode()){
         case KeyEvent.VK_LEFT:
             keyLeft = true;
             break;
         case KeyEvent.VK_RIGHT:
             keyRight = true;
             break;
        public void paintComponent(Graphics g){
        super.paintComponent(g); 
        g.drawImage(images[current[0].color],current[0].x,current[0].y,this);
        g.drawImage(images[current[1].color],current[1].x,current[1].y,this);
       // g.drawImage(images[current[2].color],current[2].x,current[2].y,this);
        //g.drawImage(images[current[3].color],current[3].x,current[3].y,this);
        class TimerAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
          if (keyLeft){
            puyoBoundsLeft(current);
            keyLeft = false;
          else if (keyRight) { 
            puyoBoundsRight(current);
            keyRight = false;
          if (current[0].y + image_height <= MAX_Y && current[1].y + image_height  <= MAX_Y)
             current[0].y += DELTA_Y;
             current[1].y += DELTA_Y;
        else {
               setAnimation(false);
           repaint();   
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class PuyoAnimation extends JPanel {
   PuyoLogic pl;   
  public PuyoAnimation() {
       pl = new PuyoLogic();       
       JButton startButton = new JButton("Start");       
       JButton stopButton  = new JButton("Stop");
       startButton.addActionListener(new Start());
       stopButton.addActionListener(new Stop());
       JPanel button = new JPanel();
       button.setLayout(new FlowLayout());
        button.add(startButton);
        button.add(stopButton);
       this.setLayout(new BorderLayout());
       this.add(button, BorderLayout.SOUTH);
        this.add(pl,BorderLayout.CENTER);
    class Start implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            pl.setAnimation(true);
    class Stop implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            pl.setAnimation(false);
}//endclass Edited by: Riz01 on Oct 14, 2009 1:35 PM

Don't use a loop to do graphics, it will make your game unresponsive and possibly draw enough resources from your machine to make the entire system unresponsive. You make a javax.swing.Timer object and using the timing there to drive your animations.

Similar Messages

  • Loop within a loop

    is there anything wrong with this code
    clear wa_bseg.
    loop at t_final into wa_final.
      loop at t_bseg1 into wa_bseg where belnr = wa_final-belnr
                                   and   gjahr = wa_final-gjahr.
    *and   zfbdt  = wa_final-zfbdt.
    if sy-subrc eq 0 .
    wa_final1 = wa_final.
    append wa_final1 to t_final1.
    clear wa_final1.
    endif.
    clear wa_bseg.
    endloop.
    *clear wa_final.
    endloop.

    Hi,
    Instead of using loop within loop , use read statement within loop it will improve program performance.
    try this below logic..
    clear wa_bseg.
    loop at t_final into wa_final.
    read table t_bseg1 into wa_bseg with key belnr = wa_final-belnr
                                                                gjahr = wa_final-gjahr.
    if sy-subrc eq 0 .
       wa_final1 = wa_final.
       append wa_final1 to t_final1.
    endif.
    clear: wa_bseg, wa_final1,wa_final.
    endloop.
    Regards,
    N M Poojari.
    Edited by: Nilambari Poojari on May 27, 2008 9:06 AM

  • Can we use Loop Statement for Ranges

    Hi Friends,
    I have a range say R_Range. I need to loop at each line item and get the values in another range R_New_Range, i have to count the number of items in R_new_range. How is it possible.
    I know range is nothing but an internal table. So we can direcly use Move statements or so ...,
    But my question is .....
    My R_range has values as below
    'I' 'EQ' '001'
    'I' 'EQ' '002'
    'I' 'BT' '003' '007'
    'I' 'EQ' '008'
    I have to move all these values to R_New_range and my count of items should be '8'.
    How can i do that????????
    Expecting ur answers....
    Thanks in advance
    Cheers,
    R.Kripa.

    hey friends,
    Its nice to see the replies.... but i think i had confused u all with the question
    Now i'll explain u all in detail ....
    See i have 15000 projects ( eg., AAA111... ) and 100 GL accounts ( eg., 123443... ) .....
    I have to get the costs from COSS and COSP tables for all the projects - GL account combinations which leads to some 1500000 entries ..... So it is giving me a SQL Dump "DBIF_RSQL_INVALID_RSQL" .........
    Description of the Dump is
    Error in the module RSQL accessing the database interface
    An exception occurred. This exception is dealt with in more detail below
    . The exception, which is assigned to the class 'CX_SY_OPEN_SQL_DB', was
    neither                                                                
    caught nor passed along using a RAISING clause, in the procedure        
    "GET_COSP_COSS" "(FORM)"                                               
    Since the caller of the procedure could not have expected this exception
    to occur, the running program was terminated.                          
    The reason for the exception is:                                        
    The SQL statement generated from the SAP Open SQL Statement violates a  
    restriction imposed by the database system used in R/3.                                                                               
    Possible errors:                                                        
    o The maximum size of an SQL statement has been exceeded.              
    o The statement contains too many input variables.                     
    o The space needed for the input data exceeds the available memory.    
    o ...                                                                               
    You can usually find details in the system log (SM21) and in the        
    developer trace of the work process (ST11).                             
    If an error occurs the developer trace often informs you about the      
    current restrictions.                                                   
    So now i want to fine tune the program so that the execution works perfectly and get me the values for all the data 1500000 :-|
    Now :
    My Projects are stored in the form of a range R_Range
    I have to loop at this range and then process 100 records at a time and then again take other 100 records .... i'll count till 100 records by getting loopaing at the range and for each loop pass i'll increment the counter ....
    I am clear till this .....
    If record consist of 'EQ' option .... then ofcourse we can consider the total record to be 1 record and we can add 1 to counter ......
    But if the record consist of 'BT' option ...... then how can we loop that and get the number of -low numbers in that range and add to my counter ????
    Hope iam clear with my question
    If not do revert back ....
    Thanks in advance for the replies
    Cheers,
    R.Kripa.
    My Doubt is ....

  • How do we use if statement in labview?moreover can i use if statement inside for loop?

    how do we use if statement in labview?moreover can i use if statement inside for loop?

    The if statement in LabVIEW is the Case structure. You can find that on the Structures palette right next to the For Loop. If you're still on the same subject about terminating a for loop early, then what you do is enclose your functions inside the loop with a case statment and make one of the case's empty except for one or more constants that you might have to wire. Hopefully, the attached picture will explain what I mean. Also, as I mentioned in one of your other posts, I think this technique is not as good as using a while loop. The array in the attached example is the same size no matter what and you may have to handle stripping extra or invalid elements.
    Attachments:
    For_Loop_with_Case.jpg ‏21 KB

  • Using a recordset in a loop statement

    Hello all,
    I am (still) trying to get an Excel spreadsheet for a dynamically created table. A crucial parameter of the problem is that I do not know the column names for my table at runtime, as it is created by a pivot query.
    I was very excited to find Tom Kyte's post on "Using a recordset in a loop statement:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:4768329722850645393::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:464820324673,
    This is precisely the solution I need. Unfortunately for me, when I create my stored procedure, it doesn't compile. As suggested I systematically renamed EXEC_SQL to DBMS_SQL, then I made some minor tweaks to integrate with HTMLDB:
    create or replace procedure export_tsv as
    connection_id DBMS_SQL.CONNTYPE
    default DBMS_SQL.default_connection;
    cursorID DBMS_SQL.CURSTYPE;
    nIgn number;
    columnValue varchar2(4000);
    ncols number;
    sep varchar2(1);
    colName varchar2(40);
    colLen number;
    coltype number;
    BEGIN
    IF DBMS_SQL.is_connected = FALSE THEN
    Message('No primary connection. Please connect.');
    RETURN;
    END IF;
    -- set up for excel spreadsheet
    htp.init;
    owa_util.mime_header ('application/vnd.ms-excel',false);
    htmldb_application.g_page_text_generated := true;
    htp.p('Content-Disposition: attachment;
    filename=myexport.txt');
    owa_util.http_header_close;
    -- end excel spreadsheet setup
    cursorID := DBMS_SQL.OPEN_CURSOR;
    DBMS_SQL.PARSE(cursorID, 'select * from exp_data', DBMS_SQL.V7);
    nIgn := DBMS_SQL.EXECUTE(cursorID);
    for i in 1 .. 1000 loop
    begin
    DBMS_SQL.describe_column( connection_id, cursorId, i,
    colName, colLen, colType );
    DBMS_SQL.define_column(cursorID, i, columnValue,
    4000 );
    exception
    when DBMS_SQL.invalid_column_number then
    ncols := i-1;
    exit;
    end;
    end loop;
    while (DBMS_SQL.fetch_rows(cursorID) > 0)
    loop
    sep := '';
    for i in 1 .. ncols loop
    DBMS_SQL.COLUMN_VALUE(cursorID, i, columnValue);
    -- print the column value
    htp.p( sep || columnValue);
    sep := chr(9);
    end loop;
    -- print the end of line CRLF
    htp.p(chr(13)|| chr(10));
    END LOOP;
    DBMS_SQL.CLOSE_CURSOR(cursorID);
    DBMS_SQL.CLOSE_CONNECTION;
    END;
    When I try to run this in the HTMLDB SQL Command Processor, I see the following error:
    ERROR at line 2: PLS-00302: component 'CONNTYPE' must be declared
    Can someone provide me with the correct translation of Tom Kyte's approach into the HTMLDB idiom?
    Thanks in advance,
    susan

    Questions about opening multiple worksheets on the web:
    I have this link that submits the page and my process calls a PL/SQL procedure that prints out an excel spreadsheet. When I hit the link again, the spreadsheet does not update. I can make the spreadsheet update from ASP or a java servlet, but never from the PL/SQL procedure. Even if I use the procedure to print out XML in XMLSS format, so that I can change worksheet name, it still does not update on successive calls.
    My code:
    PROCEDURE SQL_TO_EXCEL(p_sql in varchar2)
    as
    l_cursor integer default dbms_sql.open_cursor;
    l_status PLS_INTEGER;
    l_desc dbms_sql.desc_tab;
    l_col_cnt number;
    l_columnValue varchar2(4000);
    l_row varchar2(4000);
    l_frow PLS_INTEGER;
    l_lrow PLS_INTEGER;
    l_cols varchar2(4000);
    l_date date;
    begin
    --set mime type to Excel
    htp.init;
    owa_util.mime_header('application/vnd.ms-excel',true);
    --htp.p('Pragma: no-cache');
    --htp.p('Cache-Control: no-cache');
    --owa_util.http_header_close;
    htmldb_application.g_page_text_generated := true;
    --htp.htmlOpen;
    --htp.headOpen;
    --htp.title('SQL to Excel Export');
    --htp.headCLose;
    --htp.bodyOpen;
    execute immediate 'alter session set nls_date_format=''dd-mon-yyyy'''; -- hh24:mi:ss''';
    DBMS_SQL Calls
    dbms_sql.parse(l_cursor,rtrim(p_sql,';'),dbms_sql.native);
    l_status := dbms_sql.execute(l_cursor);
    dbms_sql.describe_columns(l_cursor,l_col_cnt,l_desc);
    l_frow := l_desc.FIRST;
    l_lrow := l_desc.LAST;
    if l_col_cnt > 0 then
    FOR colind IN l_frow..l_lrow LOOP
    l_cols := l_cols||chr(9)||l_desc(colind).col_name;
    END LOOP;
    htp.p(ltrim(l_cols,chr(9)));
    end if;
    for i in 1 .. l_col_cnt loop
    if l_desc(i).col_type = 12 then
    dbms_sql.define_column(l_cursor,i,l_date);
    else
    dbms_sql.define_column(l_cursor,i,l_columnValue,4000);
    end if;
    end loop;
    --l_status := dbms_sql.execute(l_cursor);
    while (dbms_sql.fetch_rows(l_cursor) > 0) loop
    for i in 1 .. l_col_cnt loop
    if l_desc(i).col_type = 12 then
    dbms_sql.column_value(l_cursor,i,l_date);
    l_row := l_row||chr(9)||to_char(l_date,'DD-MON-YYYY HH24:MI:SS');
    else
    dbms_sql.column_value(l_cursor,i,l_columnValue);
    l_row := l_row||chr(9)||l_columnValue;
    end if;
    end loop;
    htp.p(ltrim(l_row,chr(9)));
    l_row := '';
    end loop;
    --htp.bodyclose;
    --htp.htmlclose;
    dbms_sql.close_cursor(l_cursor);
    exception
    when others then
    dbms_sql.close_cursor(l_cursor);
    htp.p(SQLERRM||chr(10)||p_sql);
    end SQL_TO_EXCEL;
    Any ideas on how I can get the spreadsheet to update from repeated calls to the PL/SQL?

  • ASSIGNING addition  used in the LOOP statement

    Hello Guys ,
    I have a problem about at new  and at end statements, basically I want to use them in a loop with  assigning  like this :
    loop at ti_itab assigning <wa_itab>.
        at new of kunnr.
        endat.
        at end of xref1.
        endat.
    endloop.
    xref1 and kunnr are fields of my table itab , this is the correct form of do this ?  I don´t know why the at  statements are doing  control breaks for every single   register in my table ( even when both have the same value of the previous register ) , could you give me an example please. should i use  at new of <wa_itab>-kunnr it doesnt work either ?
    thank you very much,.

    Hi José,
    Click on below link:
    http://help.sap.com/saphelp_nw04/helpdata/en/9f/db9f1f35c111d1829f0000e829fbfe/content.htm
    BR
    Dep

  • Delete internal table rows without using loop statement

    i have an internal table which consists of 100 records.
    i need to keep only first 5 records.
    without using the loop statement i need to delete the rest of the records. how can we achieve this result.
    i.e.  delete itab1 where  "recordno"  > 5.
    regards.
    ZG

    Hi,
    Delete itab [FROM idx1] [TO idx2] {Where (log_exp)]
    To delete several lines at once, you have to specify at least one of the additions FROM, TO, or WHERE. You can only use the additions FROM and TO with standard tables and sorted tables.
    Delete itab [FROM idx1]
    If you specify FROM, all the table rows from the table index idx1 onwards are included.
    Delete itab [TO idx2]
    If you specify TO, all the table rows from the table index idx2 onwards are included.
    PARAMETERS: p_carrid TYPE sflight-carrid,
                p_connid TYPE sflight-connid.
    DATA: BEGIN OF seats,
            fldate    TYPE sflight-fldate,
            seatsocc  TYPE sflight-seatsocc,
            seatsmax  TYPE sflight-seatsmax,
            seatsfree TYPE sflight-seatsocc,
          END OF seats.
    DATA seats_tab LIKE STANDARD TABLE OF seats.
    SELECT fldate seatsocc seatsmax
           FROM sflight
           INTO TABLE seats_tab
           WHERE carrid = p_carrid AND
                 connid = p_connid.
    LOOP AT seats_tab INTO seats.
      seats-seatsfree = seats-seatsmax - seats-seatsocc.
      MODIFY seats_tab INDEX sy-tabix FROM seats.
    ENDLOOP.
    ENDLOOP.
    SORT seats_tab BY seatsfree DESCENDING.
    DELETE seats_tab FROM 5.
    Thanks & Regards,
    ShreeMohan
    Edited by: ShreeMohan Pugalia on Jul 21, 2009 4:28 PM

  • Normal State Button Shows Selected State At Loop Point

    My menu shows the Normal State Button Shows as the selected state At Loop Point. I want it to show for instance black until it is selected then "rollover" to red. TIA for any help.
    Murman

    There are two ways that you can do this without resorting to using a layer based shape or a layer based menu.
    First, you need to decide if it is important for the logo to appear in full colour or if you can get away with a single colour instance of it appearing. If the answer to this is that a single colour is OK, then use a standard overlay menu. Otehrwise, try using a masked overlay menu (there are limitations...)
    With a standard overlay, the background image is as you want it to appear without anything selected - all shapes and text, etc, should be in place as if no button is chosen.
    You then create the overlay, which is a simple .pict file that is the size of the menu. On this you simply place as many instances of the logo as you need - create them in black or grayscale and don't add anything else. The overlay will be mostly white with the black or gray shapes on it.
    Add this to your menu in DVDSP and drag out the button rectangles to cover the background text and the overlay shape. When the button is selected, the logo shape will show up, but will not show in the normal state.
    You can get the logo to be whatever colour you need by using the colour mapping within the property inspector for the button.
    If you definitley need a full colour logo to appear, you can either use a layer based photoshop menu, or use overlay masks:
    http://www.editorsbin.com/authoring/mask_overlay.html
    be aware that there are some limitations when using the masking technique - but all is explained in that tutorial.

  • Why use cursor and for loop?

    Hi All
    So in general why would we use a cursor and a for loop to do update in a stored procedure?
    Why wouldnt we just use a single update statement ?
    is there compelling reason for using a cursor and a for loop: I am reading some code from a co-worker that the business logic for the select (set need to be updated) is complex but the update logic is simple (just set a flag to (0 or 1 or 2 or 3 or 4).
    But eventually the select come down to a key (row_id) so I re-write it using just a single sql statement.
    The size of the main table is about 2.6 to 3million rows
    Any thoughts on that??
    The code below I just do a google for cursor for update example in case for something to play with
    -Thanks for all your input
    create table f (a number, b varchar2(10));
    insert into f values (5,'five');
    insert into f values (6,'six');
    insert into f values (7,'seven');
    insert into f values (8,'eight');
    insert into f values (9,'nine');
    commit;
    create or replace procedure wco as
      cursor c_f is
        select a,b from f where length(b) = 5 for update;
        v_a f.a%type;
        v_b f.b%type;
    begin
      open c_f;
      loop
        fetch c_f into v_a, v_b;
        exit when c_f%notfound;
        update f set a=v_a*v_a where current of c_f;
      end loop;
      close c_f;
    end;
    exec wco;
    select * from f;
    drop table f;
    drop procedure wco;
    Joining multiple tables
    create table numbers_en (
      id_num  number        primary key,
      txt_num varchar2(10)
    insert into numbers_en values (1, 'one'  );
    insert into numbers_en values (2, 'two'  );
    insert into numbers_en values (3, 'three');
    insert into numbers_en values (4, 'four' );
    insert into numbers_en values (5, 'five' );
    insert into numbers_en values (6, 'six'  );
    create table lang (
       id_lang   char(2) primary key,
       txt_lang  varchar2(10)
    insert into lang values ('de', 'german');
    insert into lang values ('fr', 'french');
    insert into lang values ('it', 'italian');
    create table translations (
      id_num    references numbers_en,
      id_lang   references lang,
      txt_trans varchar2(10) not null
    insert into translations values (1, 'de', 'eins'   );
    insert into translations values (1, 'fr', 'un'     );
    insert into translations values (2, 'it', 'duo'    );
    insert into translations values (3, 'de', 'drei'   );
    insert into translations values (3, 'it', 'tre'    );
    insert into translations values (4, 'it', 'quattro');
    insert into translations values (6, 'de', 'sechs'  );
    insert into translations values (6, 'fr', 'six'    );
    declare
      cursor cur is
          select id_num,
                 txt_num,
                 id_lang,
                 txt_lang,
                 txt_trans
            from numbers_en join translations using(id_num)
                       left join lang         using(id_lang)
        for update of translations.txt_trans;
      rec cur%rowtype;
    begin
      for rec in cur loop
        dbms_output.put (
          to_char (rec.id_num         , '999') || ' - ' ||
          rpad    (rec.txt_num        ,   10 ) || ' - ' ||
          rpad(nvl(rec.txt_trans, ' '),   10 ) || ' - ' ||
                   rec.id_lang                 || ' - ' ||
          rpad    (rec.txt_lang       ,   10 )
        if mod(rec.id_num,2) = 0 then
          update translations set txt_trans = upper(txt_trans)
           where current of cur;
           dbms_output.put_line(' updated');
        else
          dbms_output.new_line;
        end if;
      end loop;
    end;
    /Edited by: xwo0owx on Apr 25, 2011 11:23 AM

    Adding my sixpence...
    PL/SQL is not that different from a SQL perspective than any other SQL client language like Java or C# or C/C++. PL/SQL simply integrates the 2 languages a heck of a lot better and far more transparent than the others. But make no mistake in that PL/SQL is also a "client" language from a SQL perspective. The (internal) calls PL/SQL make to the SQL engine, are the same (driver) calls made to the SQL engine when using Java and C and the others.
    So why a cursor and loops in PL/SQL? For the same reason you have cursors and loops in all these other SQL client languages. There are the occasion that you need to pull data from the SQL engine into the local language to perform some very funky and complex processing that is not possible using the SQL language.
    The danger is using client cursor loop processing as the norm - always pulling rows into the client language and crunching it there. This is not very performant. And pretty much impossible to scale. Developers in this case views the SQL language as a mere I/O interface for reading and writing rows. As they would use the standard file I/O read() and write() interface calls.
    Nothing could be further from the truth. SQL is a very advance and sophisticated data processing language. And it will always be faster than having to pull rows to a client language and process them there. However, SQL is not Turing complete. It is not the procedural type language that most other languages we use, are. For that reason there are things that we cannot do in SQL. And that should be the only reason for using the client language, like PL/SQL or the others, to perform row crunching using a client cursor loop.

  • Loop statement in ABAP OO

    Hi,
    I am trying to change a BADI interface and since BADIs use ABAP OO, a simple loop statement fails to work.
    I need to loop through an internal table and for each record in the internal table I need to read another db table which has a field in common with the internal table.
    Ideally,
    Loop at lt_selections
    select logsys from /bic/mzcs_unit where /bic/zcs_unit = lt_selections-cs_unit
    endloop.
    But this piece of code fails to work in BADI because of OO concepts.
    Can anyone help me out here?
    THank you

    As Alejandro said, if you are getting a syntax error, it is probably because <b>header lines are not allow in OO</b>.
    data: wa_selections like line of lt_selections.
    Loop at lt_selections into wa_wa_selections.
    select logsys from /bic/mzcs_unit
         where /bic/zcs_unit = wa_selections-cs_unit.
    endloop.
    Regards,
    Rich Heilman
    Message was edited by: Rich Heilman

  • Regarding LOOP Statement in ABAP

    Hi,
    I have small question regarding <b>LOOP ..... ENDLOOP</b> statement against <b>SY-SUBRC</b> Check.
    I have a loop as below:
    <b> LOOP AT i_vbap WHERE vbeln = i_vbak-vbeln.
        Some Code
        ENDLOOP.
        IF sy-subrc <> 0.
          APPEND i_sdata.
          CLEAR i_sdata.
        ENDIF.</b>
    Is the above <b>Code/Syntax</b> is correct one.
    Can we use <b>SY-SUBRC</b> Check against <b>LOOP ...  ENDLOOP</b> statement.
    Is this the right way of writing the code as per standards.
    Can anybody give sujjestions regarding the same.
    Thanks in advance.
    Thanks & Regards,
    Prasad.

    Hi Prasad,
    Yes, you could use sy-subrc after the endloop. For example:
    loop at itab1 where kunnr = itab2-kunnr.
    some conditions...
    endloop.
    if sy-subrc = 0.
    write: 'Success!'.
    else.
    leave program.
    endif.
    if you press F1 while highlighting the LOOP statement here are the meaning of sy-subrc in loop...endloop.
    SY-SUBRC = 0:
    At least one loop pass was processed.
    SY-SUBRC = 4:
    The loop was not processed because the table contains no entries or no entries satisfied the conditions.
    Regards!

  • My loop statement in smartforms seems not to be working...

    Hello Experts,
    I am currently practicing smartforms and I am trying to display the records of my internal table.
    What I did was in my table under MAIN window I have put the statement:
    it_spfli into wa_spfli and also in my main area of my table I have a loop statement. Now, in one of my text
    i put wa_spfli-carrid, wa_spfli-countryfr, etc. But it still does not show any data.Help would be greatly appreciated.

    u will be getting a function module name for the smartform then
    goto se37-->enter the FM name -->search for the ITAB you r using then put a break point.
    come back to u r program the run.. controle will stops over there then check whether the data is populating or not.
    INPUT and OUTPUT patameters are for program line and INITIALIZATION tabs.. when you want to modify some data in these you need to give the veriable or ITABs u r using inside. so that system will determine the global declarations(veriable or ITAbs).
    for more info refer these links
    http://www.sap-img.com/smartforms/sap-smart-forms.htm
    http://www.sap-img.com/smartforms/smartform-tutorial.htm
    http://www.sapgenie.com/abap/smartforms.htm

  • Loop statement in oracle

    SOurce Table
    ID ADDRESS1 ADDRESS2
    11 12 QA ST. 16 SELI ST.
    12 455 LANE 3222 ROGER LANE
    Target Table:
    ID TYPE ADDRESS1 ADDRESS2
    11 NORMAL XYZ st.
    11 HIGH ABC st.
    12 NORMAL TYU st.
    12 HIGH XCV st.
    Description of Problem:
    I have a source table in which ADDRESS1 pertains to Address1 column in target table where type= 'NORMAL' and ADDRESS2 pertains to Address 2 column in target table where type = 'HIGH'
    I want to update the target table using source table on ID so that Address column in target table is updated corresponding to the ADDRESS 1 AND ADDRESS 2 columns from source table.
    I am using the following code:
    MERGE
    INTO TARGET tgt
    USING SOURCE src
    ON (src.ID = tgt.ID)
    WHEN MATCHED
    THEN
    UPDATE
    SET tgt.address1 = src.address1
    where TGT.type = '=NORMAL'
    How can i update the address2 column in the target table where type = 'HIGH'
    in one shot.
    I dont want to write two seprate queries.
    I think i can use loop statement.
    Please Advice as how to use loop, else any other suggestion.
    Thanks

    user11018028 wrote:
    SOurce Table
    ID ADDRESS1 ADDRESS2
    11 12 QA ST. 16 SELI ST.
    12 455 LANE 3222 ROGER LANE
    Target Table:
    ID TYPE ADDRESS1 ADDRESS2
    11 NORMAL XYZ st.
    11 HIGH ABC st.
    12 NORMAL TYU st.
    12 HIGH XCV st.
    Description of Problem:
    I have a source table in which ADDRESS1 pertains to Address1 column in target table where type= 'NORMAL' and ADDRESS2 pertains to Address 2 column in target table where type = 'HIGH'
    I want to update the target table using source table on ID so that Address column in target table is updated corresponding to the ADDRESS 1 AND ADDRESS 2 columns from source table.
    I am using the following code:
    MERGE
    INTO TARGET tgt
    USING SOURCE src
    ON (src.ID = tgt.ID)
    WHEN MATCHED
    THEN
    UPDATE
    SET tgt.address1 = src.address1
    where TGT.type = '=NORMAL'
    How can i update the address2 column in the target table where type = 'HIGH'
    in one shot.
    I dont want to write two seprate queries.
    I think i can use loop statement.
    Please Advice as how to use loop, else any other suggestion.
    ThanksMaybe this? If you provide scripts for create tables and sample data this wouldn't be a guess :)
    MERGE
    INTO TARGET tgt
    USING SOURCE src
    ON (src.ID = tgt.ID)
    WHEN MATCHED
    THEN
    UPDATE
    SET tgt.address1 = case when TGT.type  = 'NORMAL' then src.address1 else tgt.address1 end
    ,   tgt.address2 = case when TGT.type != 'NORMAL' then src.address2 else tgt.address2 end

  • Loop statement logic required!!!

    Dear Gurus,
    The following is used now. Need to change into Loop statement.
    Read the internal table t_ABC INTO w_ABC WITH KEY ....       "ABC is to collect all Successful Insertion
      IF sy-subrc NE 0.
        CLEAR w_ABC.
        Read the internal table t_XYZ INTO w_ABC WITH KEY ....
        IF sy-subrc EQ 0.
          PERFORM locktable.
          INSERT ABC FROM w_ABC.
          IF sy-subrc NE 0.
            w_failure = c_x.
          ENDIF.
          PERFORM unlocktable.
          APPEND w_ABC TO t_ABC.   "Here t_ABC will hv only all Successful Insertion records
          CLEAR w_ABC.
        ENDIF.
      ENDIF.
    Since there will be more than one record, I can't use READ Statement.
    How to use Loop? But it should not affect performance.
    My worry is that, if i use "Locking the table" and "Insert" inside Loop, then it will affect performance.
    Can any one please help me out?
    It's pretty urgent.
    Points will be rewarded immediately.
    Thanks & Regards,
    Neeraj

    Hi,
    Loop at t_abc INTO w_ABC .
    Read table t_XYZ INTO w_ABC WITH KEY ....
    IF sy-subrc EQ 0.
    PERFORM locktable.
    INSERT ABC FROM w_ABC.
    IF sy-subrc NE 0.
    w_failure = c_x.
    ENDIF.
    PERFORM unlocktable.
    APPEND w_ABC TO t_ABC. "Here t_ABC will hv only all Successful Insertion records
    CLEAR w_ABC.
    ENDIF.
    ENDIF.

  • Performance issue in Loop statement.

    Hi experts,
    I got an issue regarding performance in the loop statement. (IT_OUT_FINAL has huge amount of data.)
    LOOP AT it_out_final INTO wa_out_final.
    READ TABLE it_prdline_txt
    WITH KEY ydprodln = wa_out_final-prdline.
    IF sy-subrc = 0.
    wa_out_final-prdline = it_prdline_txt-ydvtext.
    MODIFY it_out_final FROM wa_out_final TRANSPORTING prdline.
    CLEAR: wa_out_final.
    ENDIF.
    read table i_sokna with key kunnr = wa_out_final-kunnr.
    if sy-subrc eq 0.
    wa_out_final-soreg = i_sokna-regio.
    MODIFY it_out_final FROM wa_out_final TRANSPORTING soreg.
    endif.
    read table i_sokna with key kunnr = wa_out_final-kunwe.
    if sy-subrc eq 0.
    wa_out_final-shreg = i_sokna-regio.
    MODIFY it_out_final FROM wa_out_final TRANSPORTING shreg.
    endif.
    clear : i_sokna,wa_out_final.
    ENDLOOP.
    Can you please help me , how to improve the performance in the above loop statement.
    Thanks,
    Revanth Kumar
    Moderator message: duplicate post locked.
    Edited by: Thomas Zloch on Jun 20, 2011 1:22 PM

    Hi,
    This one helped me in understanding the basics clearly. But I would like to further give you one example by which my question will be more clear to you and hence your further answer to it will help me in getting the idea about WHERE clause clarified.
    I was required to develop a report of all held docs by the SAP USER that were created through transaction FB60, the input obtained from user should be SAP USERNAME(obligatory).
    So the straight approach by me was that writing a SELECT-OPTIONS asking SAP USERNAME, and such username obtained from USER executing a report will be compared with the USERNAME stored in the column of table RFDT which stores all such held docs by a SAP USER that used transaction FB60 to temporarily hold it.
    So the approach used by me was using the select statement fetch all records from the column storing the SAP USERNAMES that have held docs using FB60 transaction and where clause is used to filter out only values matching the values obtained from user i.e. using SELECT-OPTIONS.
    So I was under the impression that WHERE clause can only be used in SELECT STATEMENT and not in LOOP AT...ENDLOOP.
    Now I hope my question is more clear to you. If I am not wrong, there can be two approaches,
    1) Using a SELECT statement containing the WHERE clause, fetch a resultset and then using LOOP...ENDLOOP. statement, display the output of the report using WRITE statement.
    i.e. SELECT...WHERE...ENDSELECT and then LOOP AT...ENDLOOP.
    2) Using SELECT statement, fetch all possible records and using LOOP...ENDLOOP. statement filter out the records using WHERE to match the resultset and display values in that resultset using WRITE statement
    i.e. SELECT...ENDSELECT and then LOOP AT...WHERE...ENDLOOP.
    Hope you will now be able to guide me better.
    Regards
    Ameet

Maybe you are looking for