Use of cursors insted of select statements

could any one please explain what is the advantage of using cursors instead of simple select statements
thanks
siby

A benefit to using an explicit cursor rather than a select statement, is for the NO_DATA_FOUND exception. Its kind of like a free IF statment. IF no data is found, then stop.
if you write a select statement, and no data is returned, you SHOULD code for the NO_DATA_FOUND exception. Often people say, "i'll ALWAYS get a row returned". but you should always cover your code "just in case". so you must code an exception...
declare
v_var varchar2(1);
procedure do_something(p_parm varchar2) is
begin
null;
end do_something;
procedure log_error is
begin
null;
end log_error;
begin <<main>>
do_something('x');
begin <<selectblock>>
select dummy
into v_var
from dual
where dummy = 'a';
do_something(v_var);
exception
when no_data_found then
log_error;
end selectblock;
do_something (v_var||'abc');
end main;
if you use an explicit cursor instead, you don't need to code for the NO_DATA_FOUND. If an explicit cursor opens and finds no rows, there are simply no rows. of course, you don't need a loop if you expect only 1 row returned under normal circumstances.
BTW, don' forget that SQL%ROWCOUNT and your_cursor%ROWCOUNT are not initialized. There is a null, until a row is successfully fetched. therefore if no rows are returned at all, %ROWCOUNT is NULL.
declare
v_var varchar2(1);
cursor my_cur is
select dummy
from dual
where dummy = 'a';
procedure do_something(p_parm varchar2) is
begin
null;
end do_something;
procedure log_error is
begin
null;
end log_error;
begin << main>>
for cur_rec in my_cur loop
dbms_output.put_line('inside');
begin <<loop_block>>
if nvl(my_cur%rowcount,0) > 1 then
do_something(cur_rec.dummy);
else
log_error;
end if;
end loop_block;
end loop;
end main;
/

Similar Messages

  • Using pop-up value in select statement

    Hello.
    I want to select a value from a pop-up box and then use that value in a select statement for another pop-up. Is that possible?
    The first pop-up is P39_PIIN_CALL but it is not recognized in the second pop-up when I use it in the select statemnt... select * from table where PIIN = :P39_PIIN_CALL. I get nothing back because it has no idea what :P39_PIIN_CALL is. I'm desperate and on a timeline.
    Thanks,
    Mark E

    Hi,
    After fetching the value from first popup the page should submit so that the value is availble to the second popup..
    Edit the first popup.. and in HTML Form Element Attributes and enter onchange="doSubmit('MyRequest')"
    Regards,
    Shijesh

  • Limitations in using a function within a select statement

    I have a function which retrieves various data elements from the
    database and formats it accordingly. The data (varchar2)
    returned could be in excess of 2,000 characters length.
    I need to use the returned data as part of a view. I am able to
    use the function in a "select" statement, but when I use it with
    returned data in excess of 2,000 chars, I get the following
    error:
    ORA-06502: PL/SQL: numeric or value error
    This error is occurring whenever the returned data is in excess
    of 2,000 characters.
    Is there an alternative method to what I am proposing, I have
    tried alternative data types but if I am able to use it in a
    "select" statement, I get the above error when the returned
    length exceeds 2,000 chars.
    Thanks
    Peter

    are u using oracle 7. varchar2 limit in 8 is 4000.

  • How to use bind variable in this select statement

    Hi,
    I have created this procedure where table name and fieldname is variable as they vary, therefore i passed them as parameter. This procedure will trim leading (.) if first five char is '.THE''. The procedure performs the required task. I want to make select statement with bind variable is there any possibility to use a bind variable in this select statement.
    the procedure is given below:
    create or replace procedure test(tablename in varchar2, fieldname IN varchar2)
    authid current_user
    is
    type poicurtype is ref cursor;
    poi_cur poicurtype;
    sqlst varchar2(250);
    THEVALUE NUMBER;
    begin
         sqlst:='SELECT EMPNO FROM '||TABLENAME||' WHERE SUBSTR('||FIELDNAME||',1,5)=''.THE ''';
         DBMS_OUTPUT.PUT_LINE(SQLST);
    OPEN POI_CUR FOR SQLST ;
    LOOP
         FETCH POI_CUR INTO THEVALUE;
              EXIT WHEN POI_CUR%NOTFOUND;
              DBMS_OUTPUT.PUT_LINE(THEVALUE);
              SQLST:='UPDATE '||TABLENAME|| ' SET '||FIELDNAME||'=LTRIM('||FIELDNAME||',''.'')';
              SQLST:=SQLST|| ' WHERE EMPNO=:X';
              DBMS_OUTPUT.PUT_LINE(SQLST);
                   EXECUTE IMMEDIATE SQLST USING THEVALUE;
    END LOOP;
    COMMIT;
    END TEST;
    Best Regards,

    So you want to amend each row individually? Is there some reason you're trying to make this procedure run as slow as possible?
    create or replace procedure test (tablename in varchar2, fieldname in varchar2)
    authid current_user
    is
       sqlst      varchar2 (250);
       thevalue   number := 1234;
    begin
       sqlst := 'update ' || tablename || ' set ' || fieldname || '= ltrim(' || fieldname || ',''.'')  where substr(' || fieldname
          || ',1,5) = ''.THE ''';
       dbms_output.put_line (sqlst);
       execute immediate sqlst;
    end test;will update every row that satisfies the criteria in a single statement. If there are 10 rows that start with '.THE ' then it will update 10 rows.

  • Can we use is null in our select statement in ABAP program

    hi,
    I want to use 'is nul' or 'not null' in select statement of my ABAP program for any field. I have written below query but I am getting sy-subrc = 4 and getting no data. Can anyone resolve this.

    Hi,
    I think you've posted your question on the wrong forum. This is the SAP Business One development forum which is not part of ERP and doesn't include any ABAP or Netweaver programming.
    For a list of forums please see here:
    http://forums.sdn.sap.com/index.jspa
    Kind Regards,
    Owen

  • How to use variables in an sql select statement.

    Hi, I have seen examples using the update, but nothing using a select statement.
    I have four variables I am getting from drop down menus in my JSP I set the user selected items to strings.
    How would I create the select statement like this:
    .String XName = request.getParameter("UserInputX");
    rsInResult = stmtInResult.executeQuery("SELECT ColumxX FROM TableZ WHERE ColumnX = XName")Obviously it tries to read "XName" as a column and of course can't find it, how would I set it up to have it see the Value of XName and not the literal XName.

    read this:
    rsInResult = stmtInResult.executeQuery("SELECT ColumxX FROM TableZ WHERE ColumnX = '"+XName+"')
    {code}
    better way is PreparedStatement:
    {code}
         // example code to change password to an user in the USERS table
         String newPWD = "my password";
         String user = "luxjava";
         PreparedStatement prepStat;
         String updatePWD = "UPDATE LOGISTIC.USERS "+
                                  "SET logistic.users.password = ? "+
                                  "WHERE logistic.users.username = ?";
         prepStat = ql.conDb.prepareStatement(updatePWD);
         prepStat.setString(1, newPwd);
         prepStat.setString(2, user);
         int zeroNotFound = prepStat.executeUpdate();
         if (zeroNotFound==0)
              ql.conDb.rollback();
              prepStat.close();
         else
              ql.conDb.commit();
              prepStat.close();
    {code}
    ... use the SQLException to capture errors                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problems with Hints in abap code to use an index in a Select statement

    Hi,
    I want to use an especific index in a select statement but I can´t get it. I use de next statement:
    SELECT ltaklgnum ltaktanum ltakvbeln ltaptapos ltapnltyp ltappvqui
           FROM ltak AS ltak INNER JOIN ltap AS ltap
                            ON  ltaktanum = ltaptanum
                            AND ltaklgnum = ltaplgnum
           INTO TABLE l_t_tanum_silo
           WHERE ltap~lgnum EQ ip_lgnum
             AND ltap~pquit EQ ' '
             AND ltak~lgnum EQ ip_lgnum
             AND ltak~kquit EQ ' '
             AND ltak~queue EQ ip_queue
             %_HINTS DB2 ''.
    We have DB2 for Linux Unix and Windows 9.5 as DB system.
    How can I fix this?
    Thanks a lot.
    Regards

    The DB2 for Linux Unix and Windows is coded DB6 for SAP and not DB2
    Look at the following OSS notes
    - [Note 129385 - Database hints in Open SQL|https://service.sap.com/sap/support/notes/129385]
    - [Note 150037 - Database hints in Open SQL for DB6 (DB2 for LUW)|https://service.sap.com/sap/support/notes/150037]
    - [Note 1270314 - DB6: DB2 9.5 Perf. degrad. for queries with INLIST clause|https://service.sap.com/sap/support/notes/1270314]
    - [Note 868888 - DB6: Optimization Guidelines|https://service.sap.com/sap/support/notes/868888]
    You should use a
    SELECT ltak~lgnum ltak~tanum ltak~vbeln ltap~tapos ltap~nltyp ltap~pvqui
      FROM ltak AS ltak INNER JOIN ltap AS ltap
      ON ltak~tanum = ltap~tanum
        AND ltak~lgnum = ltap~lgnum
      INTO TABLE l_t_tanum_silo
      WHERE ltap~lgnum EQ ip_lgnum
        AND ltap~pquit EQ ' '
        AND ltak~lgnum EQ ip_lgnum
        AND ltak~kquit EQ ' '
        AND ltak~queue EQ ip_queue
      %_HINTS DB6 '<IXSCAN TABLE=''LTAP'' INDEX=''"LTAP~M"'' />'.
    In note 868888 there is a sample for a join.
    SELECT A~TABSPACE
    FROM TADB6 AS A
    JOIN IADB6 AS B ON A~TABART = B~TABART
    %_HINTS DB6 '<NLJOIN><IXSCAN TABLE=''IADB6'' />'
            DB6 '<IXSCAN TABLE=''TADB6'' /></NLJOIN>'.
    Regards

  • Can use place holder (?)in select statement.

    Is it possible to have have a place holder in my select clause or it is possible to have only in where clause?
    Please find the below query I am having place holder in select statement emp_id=? nit it is throwing an error for me.
    select * from(select myrows.*, rownum rn from(select acc as account, es as identity,address as street_address
    state as stae,select id from mytable where emp_id=? as my site from myview
    where ert_id=? and chek=?
    I am getting an error ORA-00936:     missing expression is it possible to have a place holder in select statement
    Please help me on this.
    Regards,
    BA

    user575682 wrote:
    Is it possible to have have a place holder in my select clause or it is possible to have only in where clause?
    Please find the below query I am having place holder in select statement emp_id=? nit it is throwing an error for me.
    select * from(select myrows.*, rownum rn from(select acc as account, es as identity,address as street_address
    state as stae,select id from mytable where emp_id=? as my site from myview
    where ert_id=? and chek=?
    I am getting an error ORA-00936:     missing expression is it possible to have a place holder in select statement
    Please help me on this.
    Regards,
    BAfor clarity and easy to be read i attempted to rearrranged your code and this is what it will look like:
    select *
      from (select myrows.*, rownum rn
              from (select acc as account,
                           es as identity,
                           address as street_address
                           state as stae,
                           select id
                      from mytable
                     where emp_id = ? as my site from myview where ert_id=? and chek=?apparently the syntax is not correct and by that you are missing some comma in your column, ? question mark symbol will not be recognize, and some ')' closed parenthesis.
    are you using a report builder that you want to use a placeholder column?

  • Usgent: using jsp date in sql select statement

    i have something like this:
    String day;
    String month;
    String year;
    select * from event where date = xxx
    where xxx is supposed to be obtained from the strings (day, month, year) and changed into a format that can be compared to in the select statement.
    what should xxx be?
    thks as lot cos i ahe been figuring out for very long.

    Use PreparedStatement and SimpleDateFormat:
    String year = "2002";
    String month = "9";
    String day = "12";
    String sDate = day + "/" + month + "/" + year;
    SimpleDateFormat df = new SimpleDateFormat("M/d/yyyy");
    Date dDate = df.parse(sDate);
    Connection con = DriverManager.getConnection(user, pw);
    PreparedStatement ps = con.prepareStatement("SELECT * FROM event WHERE date = ?");
    ps.setDate(1, dDate);
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
    rs.close();
    ps.close();
    con.close();

  • Using Hint in Update or Select Statement...

    Hi ,
    I had an update statement that will get the data from the inline select statement,now where can i can keep the hint ,either in update statement or in Select statement...
    Please let me know if my sample script is wrong or any better way to approach...Please assume that Salary table had millions of employee's salary records.
    update emp
    set salary = salary + (select /*+ full(a) parallel(a,4)  */ salary from Salary
                             where   experience > 5  and empno = 55 )
    where empno = 85Thanks
    Rede

    The better approach would be to determine why you need a hint in the first place. If you're using a hint, that implies that the optimizer is choosing the incorrect plan when left to its own devices. That, in turn, implies that the statistics on your objects, the statistics on your system, your optimizer parameters, your session's optimizer settings or some other variable is incorrect. You're generally better off fixing the root problem than hinting every query.
    In this specific case, the parallel hint is invalid because there is no table aliased A. The full hint is invalid for similar reasons. Plus, with the query you provided, if A was intended to be the SALARY table, it seems exceptionally unlikely that you really want to do a full scan on the salary table to look for what had better be a single row (otherwise your query would throw a "too many rows returned" exception).
    Justin

  • Using a varchar field to select statement

    Hi all
    I have a single row and single column table
    T(command varchar2(4000))
    and the row is
    sno,name
    And I have another table T1(sno number,name varchar)
    Now can any body tell how can i use command column in table T to query T1 to get sno,name from T1
    I am looking for a select statement like this
    select (select command from T) from T1;
    but it is printing out the data in T i mean sno, name
    This is a copy of thread Selecting output of a select statement
    but explained more clearly
    Thanks,
    ganesh.

    I don't know why your tables are designed like this but what I think you want to do is join T1 with the data in T.
    select sno, name from T1
    where sno in (select substr(command,0,instr(command,',')-1) from T)
    and name in (select substr(command,instr(command,',')+1) from T);
    substr returns a string up to a position
    instr returns the position of a string
    and the other post you refer to as about as confusing as your one.

  • Benefit of using store procedure instead of select statement to pull data into biztalk

    I was wondering why store procedure is more beneficial than using select statement to pull data into biztalk?

    In addition to the above two points, in case if there is a change in logic of stored procedure, you only need to modify the stored proc and the applications calling/using it may be left intact.
    Also, stored procedures are complied code so performance is better and safe too.
    Thanks,
    Prashant
    Please mark this post accordingly if it answers your query or is helpful.

  • Using BEGIN TRAN for a SELECT statement

    I have inherited a number of stored procedures that are using explicit transactions and structured error handling. 
    I have had to review the procs due to deadlocks occurring and have found that many of them are SELECT statements. 
    The syntax is like this:
    BEGIN TRAN
       BEGIN TRY
    SELECT ####
     END TRY
      BEGIN CATCH
      IF @@TRANCOUNT >0
    BEGIN
    ROLLBACK TRAN
    INSERT ErrorLog
    XXXXXX
    END CATCH
    IF @@TRANCOUNT > 0
    BEGIN
    COMMIT TRAN
    END
    It is very obvious that there is no purpose for explicit transactions in the select, but I am wondering if this could be a factor in the deadlocks.  From what I tested using BEGIN TRAN for a select still only uses a shared lock. 
    Is it possible that this is a factor in the deadlocks?
    David Dye My Blog

    There is no need of explicit transaction in select statement what exactly would you want to rollback, nothing. Although you might use error handling depending on complexity of select involved.
    Plus drawbacks is locks would be held for longer duration which MIGHT provide some help in deadlock
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
    My Technet Wiki Article
    MVP

  • Are Explicit Cursors better than Select Statement

    Hi Gurus,
    I came across this opinion that explicit cursors are better (even if the query returns a single row) instead of a single row SELECT statement within the code in terms of performance.
    Is that true??? Pls elaborate in either case.
    Can i hear it from Sri/Andrew ???
    Thanks for ur time...
    Peyush

    no, it is just the opposite
    see
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:1205168148688
    for a complete explanation why
    greetings
    Freek
    Hi Gurus,
    I came across this opinion that explicit cursors are better (even if the query returns a single row) instead of a single row SELECT statement within the code in terms of performance.
    Is that true??? Pls elaborate in either case.
    Can i hear it from Sri/Andrew ???
    Thanks for ur time...
    Peyush

  • How to use LIKE keyword in a select statement

    Hi:
    I want to use the following sql statement,
    String str = "xyz";
    String query="Select * from tab where col like '"+str+"' '%' ";
    Kindly suggest
    TIA

    % is a wildcard in the like clause, so:.
    String str = "xyz";
    String query="Select * from tab where col like '%"+str+"%'";

Maybe you are looking for

  • Ahh help itunes wont open

    okay so my itunes had been working fine up until now, when i tried to open it, i got an error message that said BAD IMAGE.. either this program is not designed to run on this system or there's an error within the program. try reinstalling the softwar

  • Adobe Illustrator CC Won't Open

    Hello there. I recently purchased Creative Cloud (roughly 2 weeks ago) and downloaded Adobe Illustrator CC. For the past 2 weeks that I've had Adobe Illustrator, it's worked perfectly fine. But now, for no reason that I can find, it won't open. Every

  • SOAP to RFC scenario (SFDC - ECC synch)

    Working on a SFDC to ECC synch scenario using SOAP to RFC interface. I generated the WSDL for SFDC team and tested on soapUI, I am able to see the successful request/response structure in sxmb_moni. However, when the SFDC team is sending the request

  • Basic questions about programing for J9 VM

    I need to create a java application to run on a Pocket PC 2003 OS and I'm limited to using IBM's Websphere J9 Virtual Machine. I'm new to using java in this capacity and therefore have lots of questions which I'm guessing are pretty basic. Despite my

  • Dataguard Queston?

    Presently we have two schemas on a "development" database that developrs use for their work, we back this database up nightly using a cron job that launches EXP full=Y. They want to keep a "hot copy" of these just two schemas only on another database