Returning Recordsets from Functions

Pardon my ignorance; there is probably a simple answer to this one, but I'm trying to make the leap to Oracle Stored Procedures and I have a basic question:
I have created a Function in Oracle 8.1.7 EMP_SEL_ALL, based on the following SQL Statement:
CREATE OR REPLACE FUNCTION "SCOTT"."EMP_SEL_ALL" (
          enuma          IN NUMBER)
          RETURN SCOTT.emp%ROWTYPE IS
emp_row SCOTT.emp%ROWTYPE;
BEGIN
     SELECT * into emp_row FROM SCOTT.emp
     WHERE empno = enuma;
RETURN emp_row;
END;
The function compiles with no problems.
I have written a Java call to execute the Function, which reads as follows. Because I am attempting to return an entire row, I assume that will equate to a ResultSet:
sqlCallStmt = con.prepareCall("{ call SCOTT.EMP_SEL_ALL ? ) }");
sqlCallStmt.setInt(1, 7369);
result = sqlCallStmt.executeQuery();
The error returned is as follows:
java.sql.SQLException: ORA-06550: line 1, column 7:
PLS-00221: 'EMP_SEL_ALL' is not a procedure or is undefined
Looking in DBA Studio, the Function is shown in the SCOTT schema, and I am logged in as that user. I am therefore inclined to think that, rather than a permissions issue, I have a syntax error somewhere, or I have left out a step.
For anyone who has been down this road before, please advise. Is there a better way to do this via Stored Procedure? I have no problem querying the table and data in a standard SQL statement. Many thanks in advance.

First, when you call a function I think you have to use the syntax {call ? = function_name} (notice where the ? goes.
However, I still don't think you will be able to get this to work becuase a Java client cannot interpret a PL/SQL record (or rowtype, in your case).
If you want to return the results as a recordset, you will have to move the function into package and declare a REF CURSOR for the return type. It appears your code only returns one row, however, so a recordset will create unnecessary overhead.
It would probably be best to make your function a procedure that returns OUT parameters, one for each column selected.

Similar Messages

  • How to get the returned value from Functions with Callable statement?

    I was glad to find that stored procedures can be invoke with Java class code by the object of Callable statement like :
    String stmt = "BEGIN departments_pkg.do_select(?,?,?); END;";
    and getting the output variables by
    populateAttribute(DEPARTMENTNAME,st.getString(2),true,false);
    But i would like to get values returned from FUNCTION other than stored procedure, how can i achieve it? Thanks a lot!

    Here is  my code
    PROCESS BEFORE OUTPUT.
    MODULE STATUS_1202.
      MODULE subscreen_find.
      CALL SUBSCREEN SUBSEARCH INCLUDING sy-cprog dynnr.
    PROCESS AFTER INPUT.
      MODULE USER_COMMAND_1202.
      CALL SUBSCREEN SUBSEARCH.
    MODULE subscreen_find.
      case sy-ucomm.
        when 'SELECTED'.             "fcode
          case 'ZSKILL_SEARCH'.     "data element
            when '01'.                       " value range
              dynnr = 0110.
            when '02'.
              dynnr = 0111.
          endcase.
      endcase.
    ENDMODULE.
    kindly tell me what is wrong
    Edited by: Raji Thomas on Feb 8, 2010 10:20 AM

  • Returning arrays from function

    Hi all,
    Can u please guide me in how to return an array from function .
    Is it possible or not ??
    If it is possible please tell me how to declare the function(prototype) that returns string array
    and how to return the string array..
    Thanks in Advance

    Hi all,
    Can u please guide me in how to return an array from
    function .
    Is it possible or not ??
    If it is possible please tell me how to declare the
    function(prototype) that returns string array
    and how to return the string array..
    Thanks in Advance
    public String [] methodReturnsAnArray()
    }

  • Return value from function within package

    Hi,
    There is a function within a pl/sql package that I am trying to get data from. The problem is that the data returned can be up to 32,767 chars (varchar2 limit).
    It accepts 3 input parameters and returns on varchar2.
    The only way I can get it to work is using this syntax:
    ==================================
    variable hold varchar2(4000);
    call TrigCodeGenerator.GenerateCode(VALUE1', 'VALUE2','VALUE3') into :hold;
    print hold;
    =====================================
    However, if the data returned is greater than 4000 then I get this error:
    ERROR at line 1:
    ORA-06502: PL/SQL: numeric or value error: character string buffer too small
    ORA-06512: at line 1
    I can't increase the size of the variable (hold) as there seems to be a limitation on this type of variable.
    Also, I am running this in sql plus worksheet. Will it limit the display of the data (assuming, that someone can get the whole 32,767 chars displayed back) ?
    Thanks in advance,
    Ned

    Never mind,
    I declared the variable hold as clob and set the long and longchunksize parameters to 100,000 and it seems to work.

  • Error getting return value from function

    Hello
    I'm getting a error calling a function with ODP.NET from C#
    Code:
    OracleCommand oraCom = new OracleCommand("NORMALIZACION.nif",oraCon);
    oraCom.CommandType = CommandType.StoredProcedure;
    OracleParameter param1 = new OracleParameter("numnif",OracleDbType.Varchar2);
    param1.Value= "73667866A";
    param1.Direction = ParameterDirection.Input;
    OracleParameter param2 = new OracleParameter("nif",OracleDbType.Varchar2);
    param2.Size = 10; //FIXME line
    param2.Direction = ParameterDirection.ReturnValue;
    oraCom.Parameters.Add(param1);
    oraCom.Parameters.Add(param2);
    oraCom.ExecuteNonQuery();
    nif_norm = oraCom.Parameters["nif"].Value.ToString();
    if i write the FIXME line i get a error (ORA-06502) complaining about the size, no matter the value i wrote.
    If i don't write the FIXME line, it works but nif_norm is always empty, although the function i call is a single return 'Hello';
    Where am I wrong??
    Any help, examples with varchar2 as return value???
    BTW: the same code with the MS provider for Oracle works fine.

    Good point -- i shall do so.
    What I think I'm missing, in my quest for ODP.NET competence, is a solid set of example code. I've searched around and found various fragements here and there, but when it comes to data access from .NET there must surely be some finitie set of possibilities (if we can discount bad practices like building dynamic SQL statements without bind variables).
    For example, possibly in increasing order of complexity ...
    * Read a single value from a SQL statement ... "select emp_name from emp where rownum < 2"
    * Read a single value by passing in a parameter ... "select emp_name from emp where user_id = :?"
    * read multiple values ... "select emp_name from emp where user_id in (:?,:?)"
    * execute a stored procedure with no in or out parameters
    * retreive a value from a function with no parameters
    * pass a parameter to a stored procedure
    * read an out parameter from a stored procedure
    Then work with in and out ref cursors, blobs, whatever.
    Thoughts?

  • Returning Cursor from Function

    I have been struggling all afternoon to get a package function
    to return a cursor. Following some advice from the forums, I
    think I'm getting close. <vbg> But am getting a compile error
    on my RETURN statement. Can someone please help or post a
    working example of how to do this. Thanks!
    -- IN PACKAGE HEADER
    type package_cursor is ref cursor;
    function testfunction (p_system_date in date)
    return package_cursor;
    -- IN PACKAGE BODY
    function testfunction (p_system_date in date)
    return package_cursor is
    cursor c1 is
    select columns from tables where mydate = p_system_date;
    begin
    open c1;
    return c1;
    end testfunction;

    Nevermind, I figured it out by using Barbara Boehmer example in
    the "function returning record or table" thread.
    function testfunction (
    p_system_date in date)
    return package_cursor is
    vret package_cursor;
    begin
    open vret for
    select columns from tables where mydate = p_system_date;
    return vret;
    end testfunction;

  • Returning recordset from stored procedures

    Hi
    I am trying to get a stored procedure to return multiple values (i.e. a recordset) and want to access them from JDBC. Is that possible?
    Frankie =:>

    You can return nested tables and varrays using JDBC. See chapter 10 of the Oracle JDBC Developer's Guide.
    http://technet.oracle.com/doc/oracle8i_816/java.816/a81354/toc.htm

  • Returning objects from functions

    Hi,
    public HSSFRow someFunction() {
       HSSFRow returnrow;
       Iterator rowiterator = someobject.rowIterator();
          while(rowiterator.hasNext()) {
             returnrow = rowiterator.next();
       return returnrow;
    }My problem is this, I want to pass a HSSFRow object back from a function, but the constructor to this object is protected so i cant initialize an object, this code wont compile because it says that the returnrow object might not have been initialized. How do i get round this problem?

    Hey-
    You could just initialize returnrow to null and check for null whenever you call someFunction(), that should do it.
    Lee

  • Return variable from Function

    I have a function that if I write-host the variable $RDPUser from within the function it returns true, however I can't seem to get the variable to be seen outside the function, even if I make it global
    Function global:RDP (){
    $WorkstationName = Get-Content env:ComputerName
        # Run the qwinsta.exe and parse the output
        $queryResults = (qwinsta /server:$WorkstationName | foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv)  
        # Pull the session information from each instance
        ForEach ($queryResult in $queryResults) {
            $RDPUser = $queryResult.USERNAME
            $sessionType = $queryResult.SESSIONNAME
            # We only want to display where a "person" is logged in. Otherwise unused sessions show up as USERNAME as a number
            If (($RDPUser -match "[a-z]") -and ($RDPUser -ne $NULL)) {  
                # When running interactively, uncomment the Write-Host line below to show the output to screen
                 $LoggedOnUser = $RDPUser
             $RDPHost
                #$SessionList = $SessionList + "`n`n" + $ServerName + " logged in by " + $RDPUser + " on " + $sessionType
    #Get Current Time
    $time2 = Get-Date
    #Get Logged-On User Details
    $user = Get-WmiObject Win32_Computersystem -ComputerName "."
    #Get Time User Logged On
    $time1 = Get-EventLog -LogName System -InstanceId 7001 -Newest 1
    #Set Variables for SQL
    $LogonDateTime = get-date -Format "MMM dd yyyy HH:mm:ss"
    $WorkstationName = Get-Content env:ComputerName
    $LoggedOnUser = $user.UserName
    $TimeToLogon = $time2.TimeOfDay.TotalSeconds - $time1.TimeGenerated.TimeOfDay.TotalSeconds
    $logonType = "Logon"
    #If workstation = QATest Set $result
    if ($workstationName -eq "QAtest") {$result = RDP ; $LoggedOnUser = $result}
    write-host $LogonDateTime
    write-host $WorkstationName
    write-host $LoggedOnUser
    write-host $TimeToLogon
    write-host $logonType
    Alter De Ruine

    For some reason I needed my If statement inside the function:
    Function RDP (){
    $WorkstationName = Get-Content env:ComputerName
        # Run the qwinsta.exe and parse the output
        $queryResults = (qwinsta /server:$WorkstationName | foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv)  
        # Pull the session information from each instance
        ForEach ($queryResult in $queryResults) {
           $script:RDPUser = $queryResult.USERNAME
            $sessionType = $queryResult.SESSIONNAME
            # We only want to display where a "person" is logged in. Otherwise unused sessions show up as USERNAME as a number
            If (($RDPUser -match "[a-z]") -and ($RDPUser -ne $NULL)) {  
                # When running interactively, uncomment the Write-Host line below to show the output to screen
             $RDPUser
                #$SessionList = $SessionList + "`n`n" + $ServerName + " logged in by " + $RDPUser + " on " + $sessionType
    if ($workstationName -eq "QAV-RDHOST") {$script:LoggedOnUser = $RDPUser}
    #Get Current Time
    $time2 = Get-Date
    #Get Logged-On User Details
    $user = Get-WmiObject Win32_Computersystem -ComputerName "."
    #Get Time User Logged On
    $time1 = Get-EventLog -LogName System -InstanceId 7001 -Newest 1
    #Set Variables for SQL
    $LogonDateTime = get-date -Format "MMM dd yyyy HH:mm:ss"
    $WorkstationName = Get-Content env:ComputerName
    $LoggedOnUser = $user.UserName
    $TimeToLogon = $time2.TimeOfDay.TotalSeconds - $time1.TimeGenerated.TimeOfDay.TotalSeconds
    $logonType = "Logon"
    #Call function RDP
    RDP
    Alter De Ruine

  • Return Vector from function and print it out.

    Hey guys, I am not sure I'm doing this right. I have a class that currently has one function "getVector". This takes a string that is input and turns into a Vector array and returns the array as Vector.
    Then in the second class I simply want to print out the Vector. I get no errors, but it doesn't print anything.
    If anyone can see what I am doing wrong I'd appreciate the help.
    Thanks!
    Here is the first class that has the getVector function
    import java.util.*;
    public class GetArrays {
        public Vector getVector (String s){
            Vector theVector = new Vector();
            StringTokenizer token=new StringTokenizer(s," ");
                while (token.hasMoreTokens()){
                    String tk=token.nextToken();// get each token
                    theVector.add(tk);
                 }// end while
            return theVector;
        }//end getVector
    }//end classAnd here is the class with main that tries to print it out.
    import java.util.*;
    public class ShowArrays {
        public static void main(String[] args) {
            ShowArrays showArrays = new ShowArrays();
            Vector theArray = new Vector();
            GetArrays getArrays = new GetArrays();
            theArray = getArrays.getVector("testing this function");
            ListIterator iterator = theArray.listIterator(theArray.size());
            while(iterator.hasNext()){
                System.out.println(iterator.next()+"\n");
              }// end while
        }//end main
    }//end class

    Remove the parameter to your call to. Adding this parameter starts the iterator at the element theArray.size(), which is the end of the array.
    ListIterator iterator = theArray.listIterator();

  • How to Return Type from Function

    I've defined a type and a function in specification. But package body returns pls-00330 error (invalid use of type name or subtype name). What am I doing wrong? My intent is to write a function which will return a record containing two values. For now, I put "null;" as a placeholder.
    --specification
    CREATE OR REPLACE PACKAGE res.year_qtr AS
    TYPE yq_type IS RECORD
    (yr varchar2(2),
    qtr varchar2(1));
    FUNCTION yq_fun (date_in date)
    RETURN yq_type;
    END year_qtr;
    -body
    CREATE OR REPLACE PACKAGE BODY res.year_qtr AS
    FUNCTION yq_fun (date_in date)
    RETURN yq_type IS
    BEGIN
    null;
    RETURN year_qtr.yq_type; --get error on this line!
    END;
    END year_qtr;
    Edited by: user516543 on Mar 23, 2009 12:17 PM

    You need to declare a variable of that type and return the variable.
    You can't just return the type as it's not actually a declaration of that type.
    --specification
    CREATE OR REPLACE PACKAGE res.year_qtr AS
      TYPE yq_type IS RECORD
        (yr varchar2(2),
         qtr varchar2(1));
      FUNCTION yq_fun (date_in date)
        RETURN yq_type;
    END year_qtr;
    --body
    CREATE OR REPLACE PACKAGE BODY res.year_qtr AS
      FUNCTION yq_fun (date_in date) RETURN yq_type IS
        v_ret year_qtr.yq_type;
      BEGIN
        null;
        RETURN v_ret;
      END;
    END year_qtr;

  • Returning both raise_application_error and return value from db function...

    Hi ,
    I use Oracle 10g and forms10g.
    I have written a db packaged function such as:
    function fnc_ipologismos_xiliometron(code_poleis_apo_var in varchar2,code_poleis_pros_var in varchar2)
       return number
       is
        apostasi_var ref_apostaseis_poleon.apostasi%type;
        onomasia_pol_apo_var ref_poleis.onomasia%type;
        onomasia_pol_pros_var ref_poleis.onomasia%type;
        begin
         begin
            select onomasia into onomasia_pol_apo_var
              from ref_poleis
              where code_poleis=code_poleis_apo_var;
         end;
         begin
            select onomasia into onomasia_pol_pros_var
              from ref_poleis
              where code_poleis=code_poleis_pros_var;
         end;
         begin
          select apostasi into apostasi_var
           from ref_apostaseis_poleon
           where code_poleis_apo=code_poleis_apo_var and code_poleis_pros=code_poleis_pros_var;
          exception
           when no_data_found
    then
    apostasi_var:=0;
    return apostasi_var;
    raise_application_error(-20015,'a message');
    --return apostasi_var;
    end;      return apostasi_var;
        end;The problem is that when the exception written above (in bold) returns 0 and exits the function.... whereas i want this value to be returned as well as the message in the raise_application_error....
    I call this function in WHEN-VALIDATE-ITEM of a block item... such as:
    if pkg_mod3_general.fnc_ipologismos_xiliometron
    (:mod3_entoli_metakinisis.code_poleis_apo_type_id,:mod3_entoli_metakinisis.code_poleis_type_id)=0
                  and :mod3_entoli_metakinisis.seq_code_meso_metakin_type_id=2
                  then
                    raise form_trigger_failure;
      end if;     When the above condition is true then no message is displayed and the cursor sticks to the item(as the raise_application_error in the db packaged function is after the exit of the function) and when the condition is false then no message is displayed again ... as expected.....
    How is it get the desired result.....- get the message from the raise_application_error and the function returns 0.....?????
    Many thanks,
    Simon

    you cannot RETURN and RAISE a function.
    RETURN ends the function immediately
    RAISE ends the program unit and jumps in the EXCEPTION-Handler, if it exists. Else the function ends

  • Getting Return values from RFC function call with visual basic

    Hi,
    I am creating a sample app to connect to a SAP system which call its RFC functions created with ABAP. It was known that the function will return more than 1 return values.
       SAP Function name ==> "ZFMTP_RFC_GET_RESULT"
            Export parameters (to SAP):
                    - Student Name [char 10]         ==> "STUNAME"
                    - Student ID         [char 20]        ==> "STUID"
           Return values (From SAP):
                    - Results [char 10]        ==> "RESULT"
                    - Remarks [char 200]        ==> "REMARKS"
    i have managed to get sample codes for connecting and call a RFC function with vb but they only get a return value. How do i retrieve multiple return values like the above function "RESULT" and "REMARKS"?
    Here's my vb code to accessing the function
            Dim R3 As Object
            Dim FBFunc As Object
            Dim returnFunc As Boolean
            Dim connected As Boolean
            R3 = CreateObject("SAP.Functions")
            R3.Connection.Client = "000"
            R3.Connection.User = "BCUSER"
            R3.Connection.Password = "minisap"
            R3.Connection.Language = "DE"
            R3.Connection.System = "dtsystem"
            R3.Connection.Applicationserver = "xxx.xxx.xxx.xxx" 
            connected = R3.Connection.Logon(0, True)
            If connected <> True Then
                MsgBox("Unable to connect to SAP")
            End If
            FBFunc = R3.add("ZFMTP_RFC_GET_RESULT")
            FBFunc.exports("STUNAME") = "Jonny"
            FBFunc.exports("STUID") = "12345"
            returnFunc = FBFunc.Call() <<== How do i get the return value? or RESULT and REMARKS of the RFC Function?
    thanks alot.
    Edited by: Eugene Tan on Mar 4, 2008 7:17 AM

    Hi Gregor,
    Thanks for the link....i am having some doubts with the codes, hope you can clarify them for me if you know the codes..
    Below is the code snippet.
    Set impReturn = CHPASS_FN.Imports("RETURN")  <<=== is RETURN the standard keyword to get a                                                                                return object?
      expPassword.Value = currpass
      expNewPass.Value = newpass
      expFillRet.Value = "1"
    ''' Call change password function
      If CHPASS_FN.Call = True Then
        outFile.Write (", Called Function")
        Message = impReturn("MESSAGE") <<==== So if i have 3 return values..i just replace with the return                                                               value variable names?
        outFile.WriteLine " : " & Message
      Else
        outFile.Write (", Call to function failed")
      End If
    thanks alot...all your help is very appreciated.

  • Serial number copy functionality when creating return orders from standards

    Hi all,
    Serial number is not copying when i create return order from the standard orders in below scenario.
    I implemented one BADI for copying Serial number to Sales order when doing Post goods receipt.
    So after doing inbound delivery and PGR, serial number is copied to the sales order but when i create return order with reference to the Standard order Serial number is not copying.
    When i go VA02 for standard order and selecting the technical objects then if i create the return order serial number is copying.
    Please help me in the above issue.
    I used the following logic to copy serial number from inbound delivery PGR.
    UPDATING THE SERIAL NUMBER TO THE RESPECTINVE SALES ORDER LINE ITEMS
                CALL FUNCTION 'SERNR_ADD_TO_AU'
                  EXPORTING
                    sernr                 = lwa_sernr-sernr
                    profile               = 'NEOP'
                    material              = lwa_mseg-matnr
                    quantity              = 1
                    document              = lwa_mseg-kdauf
                    item                  = lwa_mseg-kdpos
                    debitor               = lwa_mseg-kunnr
                    vbtyp                 = 'C'
                    sd_auart              = lv_auart
                    sd_postyp             = lv_pstyv
                  EXCEPTIONS
                    konfigurations_error  = 1
                    serialnumber_errors   = 2
                    serialnumber_warnings = 3
                    OTHERS                = 4.
                IF sy-subrc = 0.
                  CALL FUNCTION 'SERIAL_LISTE_POST_AU'.
                IF sy-subrc EQ 0.
                  COMMIT WORK.
                  WAIT UP TO 2 SECONDS.
                ENDIF.
    Edited by: Rajesh Sanapala on Feb 16, 2009 12:48 PM

    hi.
    I have the same problem.
    Can you please share how you solved it?
    thank you
    Bill

  • How to test a procedure which returns a recordset from pl/sql

    hello,
    Is it possible to test a procedure which returns a recordset from pl/sql?
    Everything I try results in errors like PLS-00382: expression is of wrong type, when I try to open the result cursor
    or PLS-00221: tc is not a procedure or is undefined.
    I created the following procedure:
    CREATE OR REPLACE PACKAGE test AS
    TYPE cursorType is REF CURSOR;
    PROCEDURE test_cursor( tc IN OUT cursorType,
    v_err OUT varchar2,
    v_msg OUT varchar2);
    END;
    CREATE OR REPLACE
    PACKAGE BODY test AS
    PROCEDURE test_cursor
    (tc IN OUT cursorType,
    v_err OUT varchar2,
    v_msg OUT varchar2)
    AS
    BEGIN
    open tc for
    SELECT '1' "number" FROM dual
    union
    select '2' "number" from dual;
    v_msg := 'no errors';
    v_err := 0;
    EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
    v_msg := 'no data found';
    v_err := SQLCODE;
    WHEN OTHERS
    THEN
    v_msg := SQLERRM;
    v_err := SQLCODE;
    END;
    END;
    I try to get the output from pl/sql with something like this:
    DECLARE
    TC PROVGRON.TEST.cursorType;
    V_ERR VARCHAR2(200);
    V_MSG VARCHAR2(200);
    BEGIN
    V_ERR := NULL;
    V_MSG := NULL;
    PROVGRON.TEST.TEST_CURSOR ( TC, V_ERR, V_MSG );
    DBMS_OUTPUT.Put_Line('V_ERR = ' || V_ERR);
    DBMS_OUTPUT.Put_Line('V_MSG = ' || V_MSG);
    -- in tc I was hoping to hava a cursor??
    FOR i IN tc
    LOOP
    DBMS_OUTPUT.PUT_LINE (i.number);
    END LOOP;
    END;
    Without the for loop (or open tc) the pl/sql will output:
    V_ERR = 0
    V_MSG = no errors
    PL/SQL procedure successfully completed.
    With anything I try with the cursor I get errors?
    What am I doing wrong?

    http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch5.htm#sthref1122

Maybe you are looking for