Queries that return no results cause exception

When I run a query that returns no records, my program crashes and burns, giving me the error message that no data was found; something doesn't seem right about that. Shouldn't it be able to handle this situation? Does anyone know what I'm doing wrong? Thanks.

I'd rewrite your snippet this way:
// Here's where you get your data
String sql = "SELECT FiscalYear FROM Requests WHERE Agency = ?";                          
stmt = con.prepareStatement(sql);                     
stmt.setString(1, agency);
ResultSet result = stmt.executeQuery();                                                   
List fiscalYears = new ArrayList();
while (result.next())
    fiscalYears.add(result.getString("FiscalYear"));
result.close();
stmt.close();
// Here's where you do something with it.
int numFiscalYears = fiscalYears.size();
if (numFiscalYears > 0)
    for (int i = 0; i < numFiscalYears; ++i)
        if (i == 0)
            //if data was returned, get first row   
            //put FY value into echoPacket and send to client  
            echoPacket = DGramIt.toDatagram((String)fiscalYears.get(i), packet.getAddress(), packet.getPort());
            socket.send(echoPacket);                                                                  
        else
            //for each row of data    
            socket.receive(dummyPacket);//receive dummy packet         
            //put FY value into echoPacket and send to client      
            echoPacket = DGramIt.toDatagram((String)fiscalYears.get(i), packet.getAddress(), packet.getPort());    
            socket.send(echoPacket);   
else
    //if no data, send client message  
    //put message into echoPacket and send to client   
    echoPacket = DGramIt.toDatagram("no data", packet.getAddress(), packet.getPort());   
    socket.send(echoPacket);
}Separate out getting the results from what you do with them. - MOD

Similar Messages

  • Function that return the results of a select

    Hi,
    I would like to create a function on the famous HR oracle Departments table to select * from it. I don't know how to do it.
    Does anybody can help me?.
    Thank you

    Oracle stored functions cannot directly return result sets but can return REF CURSOR. Please read [Optimize Result Set Retrieval Using ODP.NET and Ref Cursors |http://www.oracle.com/technology/pub/articles/mastering_dotnet_oracle/williams_refcursors.html] which gives full examples in PL/SQL for server side and in VB. Net for client side.

  • Database control: how to read output of sproc that returns result set

    I have a stored procedure that returns a result set. Should I use a RowSet control to wrap this, or a database control, or neither? Am I better off with straight JDBC in a Java control?
    Thanks.

    Sorry for missing the point totally...
    DOKTL also contains long text for FM parameters...
    This is a modified version of your code that retrieves the long text and displays it...
    DATA: parameter TYPE TABLE OF swotfupar,
          ls_parameter LIKE LINE OF parameter,
          search_string TYPE doktl-object,
          texttab type table of doktl-doktext with header line.
    PARAMETERS: fubaname TYPE swcontdef-abapname
                              DEFAULT 'POPUP_TO_CONFIRM',
                pa_lang TYPE sy-langu.
    START-OF-SELECTION.
      CALL FUNCTION 'SWO_QUERY_FUNCTION_PARAMETERS'
        EXPORTING
          functionmodule            = fubaname
        TABLES
          function_parameters       = parameter
    *   EXCEPTIONS
    *     FUNCTION_NOT_FOUND        = 1
    *     OTHERS                    = 2
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *           WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      LOOP AT parameter INTO ls_parameter.
        CONCATENATE `                              `            "30 spaces
                    ls_parameter-parameter INTO search_string.
        OVERLAY search_string WITH fubaname.
        SELECT doktext FROM doktl INTO TABLE texttab
               WHERE id = 'FU'
               AND langu = pa_lang
               AND object = search_string.
        WRITE:/ 'Long Text for', ls_parameter-parameter.
        LOOP AT texttab.
          NEW-LINE.
          WRITE: AT 10 texttab COLOR COL_HEADING.
        ENDLOOP.
      ENDLOOP.
    Hope this helps you
    Regards,
    Dushyant Shetty

  • Stored procedure that returns multiple tables

    Hello everyone,
    I was wondering if there's a way to write a stored procedure that returns multiple result set as in sql server. for example, in sql server, you can write 2 select statements and when loading them in c#, u can get two data tables.
    I am not sure having a single ref cursor for each select is the only solution. I might need to return a variable number of tables per procedure call (based on a certain criteria).
    Any ideas?
    thanks for your time

    Sure. Ref cursor is the only easier answer for your problem.
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    Elapsed: 00:00:01.43
    satyaki>
    satyaki>create or replace procedure ref_gen_arg(choice in int,b in out sys_refcursor)
      2  is  
      3    str   varchar2(500);
      4  begin   
      5    if choice = 1 then      
      6      str := 'select * from emp';   
      7    elsif choice = 2 then      
      8      str := 'select * from dept';   
      9    end if;       
    10   
    11    open b for str;
    12  exception  
    13    when others then     
    14      dbms_output.put_line(sqlerrm);
    15  end;
    16  /
    Procedure created.
    Elapsed: 00:00:04.38
    satyaki>
    satyaki>
    satyaki>declare   
      2    rec_x emp%rowtype;   
      3    rec_y dept%rowtype;       
      4    w sys_refcursor;
      5  begin  
      6    dbms_output.enable(1000000);  
      7    ref_gen_arg(1,w);  
      8    loop    
      9      fetch w into rec_x;     
    10      exit when w%notfound;             
    11        dbms_output.put_line('Employee No: '||rec_x.empno||' - '||                          
    12                             'Name: '||rec_x.ename||' - '||                          
    13                             'Job: '||rec_x.job||' - '||                          
    14                             'Manager: '||rec_x.mgr||' - '||                          
    15                             'Joining Date: '||rec_x.hiredate||' - '||                          
    16                             'Salary: '||rec_x.sal||' - '||                          
    17                             'Commission: '||rec_x.comm||' - '||                          
    18                             'Department No: '||rec_x.deptno);  
    19    end loop;  
    20    close w;    
    21   
    22    ref_gen_arg(2,w);  
    23    loop    
    24      fetch w into rec_y;
    25      exit when w%notfound;            
    26         dbms_output.put_line('Department No: '||rec_y.deptno||' - '||                           
    27                              'Name: '||rec_y.dname||' - '||                           
    28                              'Location: '||rec_y.loc);  
    29    end loop;  
    30    close w;
    31  exception  
    32    when others then    
    33      dbms_output.put_line(sqlerrm);
    34  end;
    35  /
    Employee No: 9999 - Name: SATYAKI - Job: SLS - Manager: 7698 - Joining Date: 02-NOV-08 - Salary: 55000 - Commission: 3455 - Department No: 10
    Employee No: 7777 - Name: SOURAV - Job: SLS - Manager:  - Joining Date: 14-SEP-08 - Salary: 45000 - Commission: 3400 - Department No: 10
    Employee No: 7521 - Name: WARD - Job: SALESMAN - Manager: 7698 - Joining Date: 22-FEB-81 - Salary: 1250 - Commission: 500 - Department No: 30
    Employee No: 7566 - Name: JONES - Job: MANAGER - Manager: 7839 - Joining Date: 02-APR-81 - Salary: 2975 - Commission:  - Department No: 20
    Employee No: 7654 - Name: MARTIN - Job: SALESMAN - Manager: 7698 - Joining Date: 28-SEP-81 - Salary: 1250 - Commission: 1400 - Department No: 30
    Employee No: 7698 - Name: BLAKE - Job: MANAGER - Manager: 7839 - Joining Date: 01-MAY-81 - Salary: 2850 - Commission:  - Department No: 30
    Employee No: 7782 - Name: CLARK - Job: MANAGER - Manager: 7839 - Joining Date: 09-JUN-81 - Salary: 4450 - Commission:  - Department No: 10
    Employee No: 7788 - Name: SCOTT - Job: ANALYST - Manager: 7566 - Joining Date: 19-APR-87 - Salary: 3000 - Commission:  - Department No: 20
    Employee No: 7839 - Name: KING - Job: PRESIDENT - Manager:  - Joining Date: 17-NOV-81 - Salary: 7000 - Commission:  - Department No: 10
    Employee No: 7844 - Name: TURNER - Job: SALESMAN - Manager: 7698 - Joining Date: 08-SEP-81 - Salary: 1500 - Commission: 0 - Department No: 30
    Employee No: 7876 - Name: ADAMS - Job: CLERK - Manager: 7788 - Joining Date: 23-MAY-87 - Salary: 1100 - Commission:  - Department No: 20
    Employee No: 7900 - Name: JAMES - Job: CLERK - Manager: 7698 - Joining Date: 03-DEC-81 - Salary: 950 - Commission:  - Department No: 30
    Employee No: 7902 - Name: FORD - Job: ANALYST - Manager: 7566 - Joining Date: 03-DEC-81 - Salary: 3000 - Commission:  - Department No: 20
    Department No: 10 - Name: ACCOUNTING - Location: NEW YORK
    Department No: 20 - Name: RESEARCH - Location: DALLAS
    Department No: 30 - Name: SALES - Location: CHICAGO
    Department No: 40 - Name: LOGISTICS - Location: CHICAGO
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.73
    satyaki>Regards.
    Satyaki De.

  • "No results were returned by the query" exception

    Hi,
    im using postgreSql (7.2) as a backend and JDBC3 (from http://jdbc.postgresql.org/).
    im getting the exception, "No results were returned by the query" whenever i try to do an insert. the weird thing is that insert works and i can see a record in the database, but i still get this exception and i can't do anything.
    Java: 1.4.0
    thanks a lot

    you should use executeUpdate for queries that do not return result sets. that would include insert, update and delete.
    i didn't know that, that would cause a problem with postgreSql jdbc. im use to of Oracle and i never got these problems with Oracle
    this is not a problem with postgres it is a problem with your lack of understanding the API and the Oracle driver if it let's you do this is wrong.
    the API clearly states that is you try and execute a SQL statement that does not produce a ResultSet with executeQuery then a SQLException should be thrown.
    so again the postgres driver is correct you and the oracle driver are wrong.

  • Stored procedure that returns a cursor (result set)

    Hi,
    We have a stored procedure that returns a cursor (result set) but when I compliled it and catalouged (introspected) it in the OBPM I got all the primitive type parameters (either IN or OUT) in the proc call except the cursor type (the result set) which is the out param of the stored proc.
    Any pointers please?
    Thanks

    Result set is of RowType and is not supported as a Stored Procedure as far as I know.
    HTH
    Sharma

  • 2 queries should return the same result (but they dont...)

    hello
    i have a following query:
    select col1,extract(year from datum) yr, COUNT(*)
    from tableA@dblink where
    DATUM between '1-jan-1985' and '31-dec-2012'
    and col2 > 100 and col2 not in ('999999')
    and TRIM(TO_CHAR(col1)) in ('0','1')
    group by col1,extract(year from DATUM);the above query returns the count: 143 982 for year 1991
    however when i put the filter directly into this year the query returns a different number: 143 917
    select col1,extract(year from datum) yr, COUNT(*)
    from tableA@dblink  where
    DATUM between '1-jan-1991' and '31-dec-1991'
    and col2 > 100 and col2 not in ('999999')
    and TRIM(TO_CHAR(col1)) in ('0','1')
    group by col1,extract(year from DATUM);please can you help me understand why is this happening and why these 2 counts are different?
    id appreciate any tips
    thanks very much
    rgds

    UserMB wrote:
    please can you help me understand why is this happening and why these 2 counts are different?
    id appreciate any tipsThis is tricky. All others of cause are right. You must compare date columns with date values.
    If you don't explicitly compare as a date value, then it might happen that a string comparison is made.
    And if that happens both of your counts would return a wrong result. For example all dates that start with
    '4' are not counted. Like '4-jan-1991'. The string '4-jan-1991' is greater then the string '31-dec-1991'. Therefore it would not be included in the count.
    I don't think this happened. But the danger is there.
    However I have a problem seeing, what the difference between your two counts can be.
    The two important parts are the date between filter and the group by condition.
    DATUM between '1-jan-1985' and '31-dec-2012'
    DATUM between '1-jan-1991' and '31-dec-1991'
    group by col1,extract(year from DATUM);The second option returns less results than the first option. Some rows must be missing because of this different filter condition.
    If this would be a text comparison then there shouldn't be a difference. Only if it is a date comparison then this could be explained.
    Here is an example:
    Dates like 31-dec-1991 17:53:14 are included in the first count+group, but not included in the second count.
    Why? Because the string '31-dec-1991' is converted into a date. This date is 31-dec-1991 00:00:00 (midnight). Everything from this day, that is not exactly on midnight is greater than this value and therefore not included in your second query.
    So as others already pointed out you need to either truncate the date or to compare it a little differently.
    select col1,extract(year from datum) yr, COUNT(*)
    from tableA@dblink 
    where DATUM >= to_date('01-01-1991','dd-mm-yyyy')
    and  DATUM < to_date('01-01-1992','dd-mm-yyyy')
    and col2 > 100 and col2 not in ('999999')
    and TRIM(TO_CHAR(col1)) in ('0','1')
    group by col1,extract(year from DATUM);This should give the same result as your first query.
    Note that I changed the month from a month name to a number. This makes it independent from national language settings. E.g. DEZ = German, DEC = American
    Edited by: Sven W. on Oct 9, 2012 2:04 PM

  • Podcast returns "Your search returned no results" but that wasn't the case yesterday

    Hello Everyone:
    I've been a loyal listener to the 66/40 podcast. It's gone thru some name changes (now it's "66/40 on Oneplace.com") and when I did a search in AppleTV yesterday & today, I got a "Your search returned no results", even though it displays when I search for "66". For weeks now, I've been able to access it. I can access it via the iTunes Store, but no longer on AppleTV. Anyone know why? Any help would be greatly appreeshed.
    Thanks.

    Same thing happening to me, multiple podcasts, video and audio.

  • Mapping feature for queries that cannot be expressed using JDO QL

    In the "Java Data Objects vs. Entity Beans" thread at theserverside.com,
    there was a question concerning the ways to use a query that cannot be
    expressed using JDO QL (for example SQL requests having no equivalent) .
    Among the possibilities mentionned in his answers, Craig Russel said
    that a JDO implementation could map an SQL query to a Java class
    directly :
    "This might be done by a JDO vendor who mapped a user-specified SQL
    query to a JDO PC class. For example, if you have a DEPARTMENT table
    that you want to write an aggregate query for "SELECT D.DEPTID,
    MAX(E.SALARY) FROM DEPARTMENT D, EMPLOYEE E WHERE D.DEPTID = E.DEPTID".
    You would map this query to a JDO PC class DepartmentMaxSalary which has
    a key field deptid and a non-key field maxSalary. The key class
    DepartmentMaxSalaryKey has a key field deptid.
    Now, construct an instance of the key class:
    DepartmentMaxSalaryKey dk = new DepartmentMaxSalaryKey(100);
    DepartmentMaxSalary d = pm.getObjectById(dk);
    System.out.println ("Department " + d.getDeptid()
    + " has max salary of " + d.getMaxSalary());
    When the getObjectById is executed a hollow instance of
    DepartmentMaxSalary is constructed by the PersistenceManager. When the
    d.getMaxSalary() is executed, the implementation of the method accesses
    the maxSalary field which causes the PersistenceManager to executes the
    query and return the result into the field.
    No implementation to my knowledge currently offers this kind of mapping,
    but certainly some will in future."
    Do you consider in providing this kind of mapping feature in Kodo ?
    Thanks in advance.

    patrice thiebaud <[email protected]> writes:
    In the "Java Data Objects vs. Entity Beans" thread at theserverside.com,
    there was a question concerning the ways to use a query that cannot be
    expressed using JDO QL (for example SQL requests having no equivalent) .
    Among the possibilities mentionned in his answers, Craig Russel said
    that a JDO implementation could map an SQL query to a Java class
    directly :
    "This might be done by a JDO vendor who mapped a user-specified SQL
    query to a JDO PC class. For example, if you have a DEPARTMENT table
    that you want to write an aggregate query for "SELECT D.DEPTID,
    MAX(E.SALARY) FROM DEPARTMENT D, EMPLOYEE E WHERE D.DEPTID = E.DEPTID".
    You would map this query to a JDO PC class DepartmentMaxSalary which has
    a key field deptid and a non-key field maxSalary. The key class
    DepartmentMaxSalaryKey has a key field deptid.
    Now, construct an instance of the key class:
    DepartmentMaxSalaryKey dk = new DepartmentMaxSalaryKey(100);
    DepartmentMaxSalary d = pm.getObjectById(dk);
    System.out.println ("Department " + d.getDeptid()
    + " has max salary of " + d.getMaxSalary());
    When the getObjectById is executed a hollow instance of
    DepartmentMaxSalary is constructed by the PersistenceManager. When the
    d.getMaxSalary() is executed, the implementation of the method accesses
    the maxSalary field which causes the PersistenceManager to executes the
    query and return the result into the field.
    No implementation to my knowledge currently offers this kind of mapping,
    but certainly some will in future."
    Do you consider in providing this kind of mapping feature in Kodo ?Patrice,
    Sorry for the delay responding to this question. The thread dropped out
    of my awareness until Rakesh's followup question today.
    We do not currently plan on providing a mechanism for configuring JDO
    objects to load themselves from arbitrary SQL queries at this point. The
    example above seems a little contrived, for a few reasons:
    - Presumably, this aggregate salary object would be read-only.
    Read-only JDO fields/objects are a whole separate topic that we
    have chosen not to address just yet.
    - Where would the complex SQL statement go? Putting it in the
    metadata seems less than ideal, as this would make for a hideous
    metadata file, and even more complexity and more debugging
    problems than using direct JDBC SQL calls. Putting the SQL
    statement into the class also seems awkward.
    - Kodo provides a mechanism for obtaining a connection to the data
    store. When aggregate info are needed or complex,
    non-object-oriented queries must be executed, standard JDBC calls
    to the data store are probably the most appropriate approach, as
    they give you complete access to your data store.
    If we see a significant interest in these capabilities, then we may
    consider them for a future release.
    Thanks in advance.Again, I apologize for the time delay in my response. I hope that this
    answers your questions.
    -Patrick
    Patrick Linskey [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • Finally cause Exception be forgotten

    In trying out that finally cause previous return value be forgotten, as described on page 206 of "The Java Programming Language, 3rd edition", I wrote the following code, and tested it with jdk1.3.1. To my supprise, not only the return value was forgotten, the exception was appeared forgotten as well:
    class PException extends Exception {
    class Final {
        void f1(int i) {
         int result;
         System.out.println("f1("+i+")");
         try {
             result = f2(i);
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("caught an Exception: " + e);
         try {
             result = f3(i);
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("caught an Exception: " + e);
        int f2(int i) throws PException {
         try {
             if (i == 1) {
              System.out.println("generate exception");
              throw new PException();
             return 1;
         } finally {
             return 2;
        int f3(int i) throws PException {
         if (i == 1) {
             System.out.println("generate exception");
             throw new PException();
         return 1;
        public static void main(String[] args) {
         Final f = new Final();
         f.f1(1);
         f.f1(2);
         f.f1(1);
    }Here is the result:
    f1(1)
    generate exception
    result = 2
    generate exception
    caught an Exception: PException
    f1(2)
    result = 2
    result = 1
    f1(1)
    generate exception
    result = 2
    generate exception
    caught an Exception: PException

    The concern here is that when the
    try {
    finally {
    }pattern is used, without the catch block, purelly for flow control purpose, a return statement in the finally block could be problematic. If a finally block ends with a return statement, any exception that might be thrown in the try block would be ignored. The unhandled exception will not propergate, it simply lost in the midst. Because any code could throw unchecked exception, if the exception cannot afford to be lost, then one should be careful not to use return in the finally block. See the following test code:
    class Finally {
        void test() {
         int result;
         System.out.println("test()");
         try {
             result = f1();
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
         try {
             result = f2();
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
         try {
             f3();
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
         try {
             f4();
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
        int f1() {
         System.out.println("f1()");
         int a = 0;
         int b = 0;
         try {
             a = 1/0;  // this generate an unchecked exception
             b = 1;
         } finally {
             return b; // this return clobber the unchecked exception
        int f2() {
         System.out.println("f2()");
         int a = 0;
         int b = 0;
         a = 1/0; // this generate an unchecked exception
         b = 1;
         return b;
        void f3() {
         System.out.println("f3()");
         int a = 0;
         int b = 0;
         try {
             a = 1/0;  // this generate an unchecked exception
             b = 1;
         } finally {
             return;   // this return clobber the unchecked exception
        void f4() {
         System.out.println("f4()");
         int a = 0;
         int b = 0;
         try {
             a = 1/0;  // this generate an unchecked exception
             b = 1;
         } finally {
        public static void main(String[] args) {
         Finally f = new Finally();
         f.test();
    /code]
    Here are the results:test()
    f1()
    result = 0
    f2()
    Caught an Exception: java.lang.ArithmeticException: / by zero
    f3()
    f4()
    Caught an Exception: java.lang.ArithmeticException: / by zero
    We see that the devide by zero exception throw by f1() simply vanished, the unintended result 0, instead of the intended result 1, is returned. The test() method did not detect any abnormality in f1(), which is scary. To drive the point home, we try f3() and f4(), which has void return type. A simple return statement in f3() causes exception be lost. The stack frame seems intact, for otherwise, the test() method would exit abruptly before f2() even get a chance to be called.

  • The battery of my macbook died in 2 years and when I call an inform them Mr ********** (sr advisor) gets outrightly rude and tells me sorry but don't think that you can be an exception to it. Extremely shocked at this approach by apple.

    The battery of my macbook died in 2 years and when I call the servise center to inform them cuse i personally am dissapointed but at the same time want to know the reason why something like this has happened ith a product of apple. Mr ****** (sr advisor) gets outrightly rude and tells me sorry but don't think that you can be an exception to it. Extremely shocked at this approach by apple. Then throughout the conversation he chose to mute me and wouldnt answer my queries. And when i asked him whos the serior I could talk to. He tells me "Im the seriormost that you can get upto..there is nobody above me you can talk to".
    Now what do i do???
    <Edited by Host>

    By doing so, you are violating the terms of use of this support forum
    "Post constructive comments and questions. Unless otherwise noted, your Submission should either be a technical support question or a technical support answer. Constructive feedback about product features is welcome as well. If your Submission contains the phrase “I’m sorry for the rant, but…” you are likely in violation of this policy."
    "Breach of the Agreement
    If you fail to abide by these terms Apple may remove your submission. Apple may also send an e-mail that informs you that your Submission has been deleted or edited. Repeated inappropriate Submissions may result in your relevant account or accounts being placed into temporary or permanent suspension of your ability to participate in any or all of the areas on the Site."
    https://discussions.apple.com/static/apple/tutorial/tou.html

  • SOLVED: How can I use or call a function that returns %ROWTYPE?

    Hi
    edit: you can probably skip all this guff and go straight to the bottom...In the end this is probably just a question of how to use a function that returns a %rowtype.  Thanks.
    Currently reading Feuerstein's tome, 5th ed. I've downloaded and run the file genaa.sp, which is a code generator. Specifically, you feed it a table name and it generates code (package header and package body) that will create a cache of the specified table's contents.
    So, I ran:
    HR@XE> @"C:\Documents and Settings\Jason\My Documents\Work\SQL\OPP5.WEB.CODE\OPP5.WEB.CODE\genaa.sp"
    749  /
    Procedure created.
    HR@XE> exec genaa('EMPLOYEES');which generated a nice bunch of code, viz:
    create or replace package EMPLOYEES_cache is
        function onerow ( EMPLOYEE_ID_in IN HR.EMPLOYEES.EMPLOYEE_ID%TYPE) return HR.EMPLOYEES%ROWTYPE;
        function onerow_by_EMP_EMAIL_UK (EMAIL_in IN HR.EMPLOYEES.EMAIL%TYPE) return HR.EMPLOYEES%ROWTYPE;
        procedure test;
    end EMPLOYEES_cache;
    create or replace package body EMPLOYEES_cache is
        TYPE EMPLOYEES_aat IS TABLE OF HR.EMPLOYEES%ROWTYPE INDEX BY PLS_INTEGER;
        EMP_EMP_ID_PK_aa EMPLOYEES_aat;
        TYPE EMP_EMAIL_UK_aat IS TABLE OF HR.EMPLOYEES.EMPLOYEE_ID%TYPE INDEX BY HR.EMPLOYEES.EMAIL%TYPE;
        EMP_EMAIL_UK_aa EMP_EMAIL_UK_aat;
        function onerow ( EMPLOYEE_ID_in IN HR.EMPLOYEES.EMPLOYEE_ID%TYPE)
            return HR.EMPLOYEES%ROWTYPE is
            begin
                return EMP_EMP_ID_PK_aa (EMPLOYEE_ID_in);
            end;
        function onerow_by_EMP_EMAIL_UK (EMAIL_in IN HR.EMPLOYEES.EMAIL%TYPE)
            return HR.EMPLOYEES%ROWTYPE is
            begin
                return EMP_EMP_ID_PK_aa (EMP_EMAIL_UK_aa (EMAIL_in));
            end;
        procedure load_arrays is
            begin
                FOR rec IN (SELECT * FROM HR.EMPLOYEES)
                LOOP
                    EMP_EMP_ID_PK_aa(rec.EMPLOYEE_ID) := rec;
                    EMP_EMAIL_UK_aa(rec.EMAIL) := rec.EMPLOYEE_ID;
                end loop;
            END load_arrays;
        procedure test is
            pky_rec HR.EMPLOYEES%ROWTYPE;
            EMP_EMAIL_UK_aa_rec HR.EMPLOYEES%ROWTYPE;
            begin
                for rec in (select * from HR.EMPLOYEES) loop
                    pky_rec := onerow (rec.EMPLOYEE_ID);
                    EMP_EMAIL_UK_aa_rec := onerow_by_EMP_EMAIL_UK (rec.EMAIL);
                    if rec.EMPLOYEE_ID = EMP_EMAIL_UK_aa_rec.EMPLOYEE_ID then
                        dbms_output.put_line ('EMP_EMAIL_UK  lookup OK');
                    else
                        dbms_output.put_line ('EMP_EMAIL_UK  lookup NOT OK');
                    end if;
                end loop;
            end test;
        BEGIN
            load_arrays;
        end EMPLOYEES_cache;
    /which I have run successfully:
    HR@XE> @"C:\Documents and Settings\Jason\My Documents\Work\SQL\EMPLOYEES_CACHE.sql"
    Package created.
    Package body created.I am now trying to use the functionality within the package.
    I have figured out that the section
        BEGIN
            load_arrays;
        end EMPLOYEES_cache;
    /is the initialization section, and my understanding is that this is supposed to run when any of the package variables or functions are referenced. Is that correct?
    With that in mind, I'm trying to call the onerow() function, but it's not working:
    HR@XE> select onerow(100) from dual;
    select onerow(100) from dual
    ERROR at line 1:
    ORA-00904: "ONEROW": invalid identifier
    HR@XE> select employees_cache.onerow(100) from dual;
    select employees_cache.onerow(100) from dual
    ERROR at line 1:
    ORA-06553: PLS-801: internal error [55018]
    HR@XE> select table(employees_cache.onerow(100)) from dual;
    select table(employees_cache.onerow(100)) from dual
    ERROR at line 1:
    ORA-00936: missing expressionHe provides the code genaa.sp, and a very brief description of what it does, but doesn't tell us how to run the generated code!
    Now, I have just done some googling, and it seems that what I am trying to do isn't possible. Apparently %ROWTYPE is PL/SQL, and not understood by SQL, so you can't call onerow() from sql. Correct?
    So I try wrapping the call in an exec:
    HR@XE> exec select employees_cache.onerow(100) from dual;
    BEGIN select employees_cache.onerow(100) from dual; END;
    ERROR at line 1:
    ORA-06550: line 1, column 30:
    PLS-00382: expression is of wrong type
    ORA-06550: line 1, column 7:
    PLS-00428: an INTO clause is expected in this SELECT statement
    HR@XE> exec select table(employees_cache.onerow(100)) from dual;
    BEGIN select table(employees_cache.onerow(100)) from dual; END;
    ERROR at line 1:
    ORA-06550: line 1, column 14:
    PL/SQL: ORA-00936: missing expression
    ORA-06550: line 1, column 7:
    PL/SQL: SQL Statement ignored
    HR@XE> exec employees_cache.onerow(100)
    BEGIN employees_cache.onerow(100); END;
    ERROR at line 1:
    ORA-06550: line 1, column 7:
    PLS-00221: 'ONEROW' is not a procedure or is undefined
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignoredNo joy.
    Of course, now that I'm looking at it again, it seems that the way to go is indicated by the first error:
    PLS-00428: an INTO clause is expected in this SELECT statement
    So am I supposed to create a type of EMPLOYEES%ROWTYPE in a PL/SQL procedure, and the idea of this code, is that the first call to onerow() runs the initialiation code, which populates the cache, and all subsequent calls to onerow() (whether by my session or any other) will use the cache?
    I've had a stab at this, but still, no joy:
    create or replace procedure testcache is
        emp employees%rowtype;
        begin
            select employees_cache.onerow(100) from dual into emp;
            dbms_output.put_line('Emp id: ' || emp.employee_id);
        end testcache;
    show errors
    HR@XE> @testcache.sql
    Warning: Procedure created with compilation errors.
    Errors for PROCEDURE TESTCACHE:
    LINE/COL ERROR
    4/9      PL/SQL: SQL Statement ignored
    4/54     PL/SQL: ORA-00933: SQL command not properly ended
    HR@XE>Have a feeling this should be really easy. Can anybody help?
    Many thanks in advance.
    Jason
    Edited by: 942375 on 08-Feb-2013 11:45

    >
    Ha, figured it out
    >
    Hopefully you also figured out that the example is just that: a technical example of how to use certain Oracle functionality. Unfortunately it is also an example of what you should NOT do in an actual application.
    That code isn't scaleable, uses expensive PGA memory, has no limit on the amount of memory that might be used and, contrary to your belief will result in EVERY SESSION HAVING ITS OWN CACHE of exactly the same data if the session even touches that package.
    Mr. Feuerstein is an expert in SQL and PL/SQL and his books cover virtually all of the functionality available. He also does an excellent job of providing examples to illustrate how that functionality can be combined and used. But the bulk of those examples are intended solely to illustrate the 'technical' aspects of the technology. They do not necessarily reflect best practices and they often do not address performance or other issues that need to be considered when actually using those techniques in a particular application. The examples show WHAT can be done but not necessarily WHEN or even IF a given technique should be used.
    It is up to the reader to learn the advantages and disadvantages of each technicalogical piece and determine when and how to use them.
    >
    Now, I have just done some googling, and it seems that what I am trying to do isn't possible. Apparently %ROWTYPE is PL/SQL, and not understood by SQL, so you can't call onerow() from sql. Correct?
    >
    That is correct. To be used by SQL you would need to create SQL types using the CREATE TYPE syntax. Currently that syntax does not support anything similar to %ROWTYPE.
    >
    So am I supposed to create a type of EMPLOYEES%ROWTYPE in a PL/SQL procedure, and the idea of this code, is that the first call to onerow() runs the initialiation code, which populates the cache, and all subsequent calls to onerow() (whether by my session or any other) will use the cache?
    >
    NO! That is a common misconception. Each session has its own set of package variables. Any session that touches that package will cause the entire EMPLOYEES table to be queried and stored in a new associative array specifically for that session.
    That duplicates the cache for each session using the package. So while there might be some marginal benefit for a single session to cache data like that the benefit usually disappears if multiple sessions are involved.
    The main use case that I am aware of where such caching has benefit is during ETL processing of staged data when the processing of each record is too complex to be done in SQL and the records need to be BULK loaded and the data manipulated in a loop. Then using an associative array as a lookup table to quickly get a small amount of data can be effective. And if the ETL procedure is being processed in parallel (meaning different sessions) then for a small lookup array the additional memory use is tolerable.
    Mitigating against that is the fact that:
    1. Such frequently used data that you might store in the array is likely to be cached by Oracle in the buffer cache anyway
    2. Newer versions of Oracle now have more than one cache
    3. The SQL query needed to get the data from the table will use a bind variable that eliminates repeated hard parsing.
    4. The cursor and the buffer caches ARE SHARED by multiple sessions globally.
    So the short story is that there would rarely be a use case where ARRAYs like that would be preferred over accessing the data from the table.

  • Call RFC that return structure using VB

    Hi, anyone has a sample code to call a custom RFC that returns table structure?
    The RFC expect parameters to pinpoint the record and return it in a structure.
    *Local Interface:
    IMPORTING
    VALUE(CUSTOMER) LIKE KNA1-KUNNR
    VALUE(MATERIAL) LIKE MARA-MATNR
    VALUE(POSTING_DATEFR) LIKE BKPF-BUDAT
    VALUE(POSTING_DATETO) LIKE BKPF-BUDAT
    TABLES
    SALES_VOLUME STRUCTURE ZRRPS_SALES
    Here's my vb code, but it return zero entries (I'm sure it should return records).
    ***Login Process Here***
    Set objFunc = objSAPLogon.Add("Z_CUSTOM_SALES_DATA")
    Set objSALES = objFunc.Tables("SALES_VOLUME")
    With objFunc
    .Exports("CUSTOMER") = "1234567"
    .Exports("MATERIAL") = "1234"
    .Exports("POSTING_DATEFR") = "10012005"
    .Exports("POSTING_DATETO") = "10312005"
    End With
    If Not objFunc.Call Then
    Debug.Print objFunc.Exception
    Exit Sub
    End If
    Debug.Print objSALES.RowCount ==> 0
    From here, I dont know what to do next. Am I missing something? Please help.
    Thanks in advance!
    /Noel

    Yes, the RFC developer told me to use this format mmddyyyy.
    I think the Exports portion is not working, and I dont know why. I tried remarking the Exports portion and it gives the same result, zero entries.
    Thanks!

  • Sort/filter datablock based on procedure that return table type

    Hi All,
    I’ve got datablock based on procedure that return table type. In the form I have to provide ‘filter and sort records’ functionality. Previously, using tables/views based datablocks, I’ve done that by using:
    -- filter
    SET_BLOCK_PROPERTY (L_BLOCK_NAME, DEFAULT_WHERE, L_WHERE_CLAUSE);
    -- sort
    SET_BLOCK_PROPERTY(L_BLOCK_NAME ,ORDER_BY, L_ORDER_BY_CLAUSE);
    -- and then
    EXECUTE_QUERY;
    It doesn’t work with procedure that return table type. How I can do that?
    Bartek

    I agree with Andreas, from the sample you have given us, I don't see any reason why you could not merge these queries into a single UNION/UNION ALL query. Also, I would add your summation query to your main query to eliminate this extra step. The result would look something like:
    SELECT DISTINCT
         pih.id
         ,d.document_id
         ,pih.doc_serial_no
         ,pih.purch_invoice_date
         ,oh.company_name
         ,(SELECT NVL(SUM(amount),0)
              FROM "YOUR TABLE HERE" yth
              WHERE yth."YOUR COLUMN HERE" = pih.id) AS sum_amount
      FROM "YOUR TABLES HERE"
    WHERE "YOUR JOIN CONDITIONS HERE"
    UNION ALL
    SELECT DISTINCT
         sih.id
         ,d.document_ind
         ,sih.doc_serial_no
         ,sih.sales_invoice_date
         ,sih.company_name
         ,(SELECT NVL(SUM(amount),0)
              FROM "YOUR TABLE HERE" yth
              WHERE yth."YOUR COLUMN HERE" = sih.id) AS sum_amount
      FROM "YOUR TABLES HERE"
    WHERE "YOUR JOIN CONDITIONS HERE"
    [/code]
    Hope this helps.
    Craig...
    +If a response is helpful or correct, please mark it accordingly+
    Edited by: CraigB on Feb 23, 2010 1:39 PM
    It appears the CODE tags are not working as well as the URL tags.  :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Web Service Method that returns an ArrayList

    Hi guys,
    I have to create a web service method that returns an ArrayList, but it's not working. My problem is:
    With the "@XmlSeeAlso" annotation, my client prints the result, but the ArryaList is not from java.util, it's from org.me.calculator so I can't use it.
    If I remove this annotation, I get no result, with this error message on Tomcat 6:
    [javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.]
    I'm a newbie, and trying to understand web services (I read some posts here, but didn't get the point, from its answers), but this problem I just can't figure out how to solve....
    WEb Service
    package org.me.calculator;
    import java.io.Serializable;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import java.util.*;
    import java.util.ArrayList;
    import javax.xml.bind.annotation.XmlSeeAlso;
    * @author eduardo.domanski
    @WebService()
    @XmlSeeAlso({java.util.ArrayList.class}) // With this, I can see the result on client, but, the ArrayList is an org.me.calculator.ArrayList class.... Strange...
    public class CalculatorWS {
        @WebMethod(operationName = "valores")
        public ArrayList valores(@WebParam(name = "a") int a,
                           @WebParam(name = "b") int b) {
            ArrayList teste = new ArrayList();
            ArrayList a1 = new ArrayList();
            a1.add(a);
            a1.add(b);
            ArrayList a2 = new ArrayList();
            a2.add(a+b);
            a2.add(a-b);
            teste.add(a1);
            teste.add(a2);
            return  teste; 
    }CLient
    package org.me.calculator.client;
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ClientServlet extends HttpServlet {
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ClientServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ClientServlet at " + request.getContextPath() + "</h1>");
            try { // Call Web Service Operation
                org.me.calculator.CalculatorWSService service = new org.me.calculator.CalculatorWSService();
                org.me.calculator.CalculatorWS port = service.getCalculatorWSPort();
                // TODO initialize WS operation arguments here
                int i = 8;
                int j = -6;
                // TODO process result here
                ArrayList result = (ArrayList) port.valores(i, j);
                out.println("Result = " + result);
            } catch (Exception ex) {
                System.out.println(ex);
            // TODO handle custom exceptions here
            out.println("</body>");
            out.println("</html>");
            out.close();
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
    }THank you all,
    Eduardo
    Edited by: EduardoDomanski on Apr 23, 2008 4:40 AM

    I forgot to say that, when I try to return an ArrayList of an object, for example, ClassA, which is on the package org.me.classes, on my Server App, the ArrayList is returned, but the objects are from type org.me.calculator.ClassA. It should be from org.me.classes.ClassA, right?
    This package also exists on my client App, to use the object, but as the returned type is from another package, I can't even cast it. I tried some annotations @Xml... but it failed.
    Packages
    ServerApp
    org.me.calculator
    CalcWS.java
    org.me.classes
    ClassA.java
    Client App
    org.me.classes
    ClassA.java
    The return from my method should be an ArrayList of org.me.classes.ClassA, but when I print it, on client, it's from org.me.calculator.ClassA.
    Does anybody knows, or had the same problem?
    Thanks,
    Eduardo

Maybe you are looking for

  • Certain albums won't play on Iphone but still play perfectly fine in Itunes

    Since I updated my Iphone to IOS5, certain albums won't play. They work perfectly fine in Itunes on my imac and the still appear in my library on the Iphone, but it won't start playing. The strange thing is, they are all albums from this year. All th

  • Vendor Return w/ replaced part

    Hi All: I have situation in the vendor return scenario, customer most of the time return the goods to vendor if the it bad part or part failed and it is still under warranty. in any case vendor never gives the credit back rather he sends the new part

  • How to veto a JComboBox selection change in ItemListener

    I have a JComboBox whose current value is tied to some data cached in my application. I want to be able to examine the selection in an ItemListener attached to the JComboBox, and if the value is different than what I have cached, I want to ask the us

  • Apple Hardware Test & My Power Supply

    I was wondering if the Apple Hardware Test does any check on the Power Supply. I was planning on replacing mine on a Mac Pro (Early 2008). I have been having a constant freeze from wake issue, and the system refuses to power on from a cold start unle

  • Characteristic display after Key Figures

    Hi, I need to display a characteristic in last coloumn of the report. i.e., after all the key figures. is it possible ?? regards, KV