How to print/store in file the ref cursor in pl/sql block ?

How to print/store in file the ref cursor in pl/sql block ?.

How to print/store in file the ref cursor in pl/sql block ?.You question is quite confusing?
So, i'm providing link in this manner.
For RefCursor,
http://www.oracle-base.com/articles/misc/UsingRefCursorsToReturnRecordsets.php
http://www.oracle.com/technology/oramag/code/tips2003/042003.html
For UTL_FILE,
http://www.morganslibrary.org/reference/utl_file.html
Regards.
Satyaki De.
Updated with new morgan library link.
Edited by: Satyaki_De on Feb 24, 2010 9:03 PM

Similar Messages

  • REF CURSOR in PL/SQL BLOCK

    I am trying to return a ref cursor from a function in a package. I am trying to execute this through SQL Plus and cannot seem to get the code correct this is what I have. Please help. How do I display the output? I tried a CURSOR FOR loop, but got syntactical error saying it was being used inproperly.
    DECLARE
         v_rec      adp_vsp.grc_vsp;
         v_fname ps_personal_data.first_name%TYPE;
         v_lname ps_personal_data.last_name%TYPE;
    BEGIN
         v_fname := 'John';
         v_lname := 'Barr';
         v_rec := adp_vsp.f_get_vsp(v_fname,v_lname);
    END;

    If you want to do it manually, you need to loop through the cursor and fetch the results:
    sql>create or replace procedure p_show_emps(p_rc out sys_refcursor)
      2  is
      3  begin
      4    open p_rc for select empno, ename from emp where rownum <= 5;
      5  end;
      6  /
    Procedure created.
    sql>declare
      2    v_rc     sys_refcursor;
      3    v_empno  emp.empno%type;
      4    v_ename  emp.ename%type;
      5  begin
      6    p_show_emps(v_rc);
      7    loop
      8      fetch v_rc into v_empno, v_ename;
      9      exit when v_rc%notfound;
    10      dbms_output.put_line( v_empno || ', ' || v_ename );
    11    end loop;   
    12    close v_rc;
    13  end;
    14  /
    7369, SMITH
    7499, ALLEN
    7521, WARD
    7566, JONES
    7654, MARTIN
    PL/SQL procedure successfully completed.

  • How to print a HTML file in browser look using DocPrintJob

    Hello guys,
    Does anyone know how to print HTML output/file into browser look?
    I'm using DocPrintJob and the DocFlavor set to DocFlavor.INPUT_STREAM.AUTOSENSE.
    posted below is my code :
    public class BasicPrint {
        public static void main(String[] args) {
            try {
                // Open the image file
                String testData = "C:/new_page_1.html";
                InputStream is = new BufferedInputStream(new FileInputStream(testData));
                DocFlavor flavor =  DocFlavor.INPUT_STREAM.AUTOSENSE;
                // Find the default service
                PrintService service = PrintServiceLookup.lookupDefaultPrintService();
                System.out.println(service);
                // Create the print job
                DocPrintJob job = service.createPrintJob();
                Doc doc= new SimpleDoc(is, flavor, null);
                // Monitor print job events; for the implementation of PrintJobWatcher,
                // see e702 Determining When a Print Job Has Finished
                PrintJobWatcher pjDone = new PrintJobWatcher(job);
                // Print it
                job.print(doc, null);
                // Wait for the print job to be done
                pjDone.waitForDone();
                // It is now safe to close the input stream
                is.close();
            } catch (PrintException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
        static class PrintJobWatcher {
            // true iff it is safe to close the print job's input stream
            boolean done = false;
            PrintJobWatcher(DocPrintJob job) {
                // Add a listener to the print job
                job.addPrintJobListener(new PrintJobAdapter() {
                    public void printJobCanceled(PrintJobEvent pje) {
                        allDone();
                    public void printJobCompleted(PrintJobEvent pje) {
                        allDone();
                    public void printJobFailed(PrintJobEvent pje) {
                        allDone();
                    public void printJobNoMoreEvents(PrintJobEvent pje) {
                        allDone();
                    void allDone() {
                        synchronized (PrintJobWatcher.this) {
                            done = true;
                            PrintJobWatcher.this.notify();
            public synchronized void waitForDone() {
                try {
                    while (!done) {
                        wait();
                } catch (InterruptedException e) {
    }the printed ouput for this code will be look like this
    <html>
    <body>
    <div style="page-break-after:'always';
                background-color:#EEEEEE;
                width:400;
                height:70">
         testPrint</div>
    ABCDEFGHIJK<p>
     </p>
    </body>
    </html>however, the output that i want is the HTML in browser look not HTML code itself.
    i've tried to change the DocFlavor into any TEXT_HTML type but it gives error:
    sun.print.PrintJobFlavorException: invalid flavor if you guys has any idea or solution, can you share with me... already search in Google but still not found any solution
    Thanks in advanced.

    hi,
    do the following
    URL url = null;
    try
         url = new URL("http://www.xyz.com");
    catch (MalformedURLException e)
          System.out.println("URL not correct " + e.toString());
    if (url != null)
           getAppletContext().showDocument(url,"_blank"); //shows the page in a new unnamed top level browser instance.
    }hope that helpz
    cheerz
    ynkrish

  • How to print a pdf file from Labview

    Hi,
    Does anyone know how to print a pdf file form Labview. I need to be able to point on the pdf file and to print it.
    Activex examples doesnt seem to be working it always displays an error, on every PC that I tryed to run it.
    {"code 3005" ,,,"Automation Open: Object specified is not creatable in Display PDF in Dialog.vi"}.
    Thank you for your help.
    Regards,
    Jenia.

    You can use the "System Exec.vi". The command line should have the following structure:
    "<Path to AcroRd32.exe>" /t "<Path to document>" "Printer name"
    For example"
    "C:\Program Files\Adobe\Acrobat 5.0\Reader\AcroRd32.exe" /t "C:\myreport.pdf" "Tektronix Phaser 300i"
    Regards;
    Enrique
    www.vartortech.com

  • How to print a pdf file of compounds A3 and A4 with adobe mac

    how to print a pdf file of compounds A3 and A4 with adobe mac, windows with the option I choose paper source by PDF page size mac but I can not find it. how to get it thank you

    I think if you use the start-command, the execution is asynchronously and you won't get the correct process-id. Try to execute Acorbat directly without the cmd /c start in front of it.

  • How to print a PDF file that was display in my page...

    Hi !. My doubt would be the following one... I would like to know how to print a pdf file that was displayed in my page ?... I mean the PDF file not the page...
    The PDF would be in this url:
    http://iprodesa.lasegunda.com.ar:8090/datos/pdf/830.pdf
    How could I implement this ?...

    This first question which comes to mind is how do you display the pdf file in the browser?
    For this the browser uses a plug in (e.g. adobe reader) which already has the ability to print the pdf file. Depending on the version of your plug in, printing is started differently.
    Timo
    Ps: which jdev version do you use?

  • How to handle the ref cursor which is returning "no rows"

    I have written a function which is returning the REF CURSOR. But in one situation the REF CURSOR returns "no rows selected". To handle this situation an exception is raised "when no data found". But i dont know in this situation how should NULL cursor be returned through this function. Since I want to call this function in another procedure so something should be returned through this function by means of ref cursor. But since i am not able to handle this "no rows selected" situation i am not able move further.
    Thanks in advance........

    I agree.
    You would simply process the returned ref cursor irrespective of any rows actually returned in the cursor or not. You would be able to do at least one FETCH from the cursor (even if it does not actually contain any rows) and then determine the %NOTFOUND status to do the rest of the processing.
    SQL> variable cur refcursor
    SQL> exec open :cur for select * from scott.emp where rownum = 1 ;
    PL/SQL procedure successfully completed.
    SQL> print cur
         EMPNO ENAME      JOB              MGR HIREDATE           SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-1980        800                    20
    1 row selected.
    SQL>
    SQL> exec open :cur for select * from scott.emp where 1 = 2 ;
    PL/SQL procedure successfully completed.
    SQL> print cur
    no rows selected
    SQL>
    SQL> SET SERVEROUTPUT ON
    SQL> DECLARE
      2      rec scott.emp%ROWTYPE;
      3      bol BOOLEAN;
      4      cur sys_refcursor;
      5  BEGIN
      6      OPEN cur FOR
      7          SELECT * FROM scott.emp WHERE 1 = 2; /* assume this is your function call returning a ref cursor */
      8      bol := FALSE;
      9      LOOP
    10          FETCH cur
    11              INTO rec;
    12          EXIT WHEN cur%NOTFOUND;
    13          --
    14          -- process the data here
    15          --
    16          bol := TRUE;
    17      END LOOP;
    18      CLOSE cur;
    19      IF (bol)
    20      THEN
    21          dbms_output.put_line('At least one row was found');
    22      ELSE
    23          dbms_output.put_line('No rows were selected');
    24      END IF;
    25  END;
    26  /
    No rows were selected
    PL/SQL procedure successfully completed.
    SQL>

  • Please help : How to print a matrix from the console...

    Hi..
    Please help:
    How to print a matrix on the console , but i want to take all the input from the console.. like...
    if the matrix is of size...
    mxn
    where
    m : row
    n : column
    and the all the elements of the matrix from the console it self... .
    Please help...

    Thanks...
    I am able to print the elements of the array but i am not able to assign those values to the array ....
    How to do that...
    I just did a little change in my code...
    import java.util.Scanner;
    public class CreatingAMatrix {
        public static void main(String[] args) {
         // TODO Auto-generated method stub
         System.out.print("Enter the number of rows: ");
         Scanner scanner1 = new Scanner(System.in);
         int m = scanner1.nextInt();
         System.out.print("Enter the number of coulmns:");
         Scanner scanner2 = new Scanner(System.in);
         int n = scanner2.nextInt();
         System.out.println("The size of the matrix is : " +m+" x "+n );
         int[][] a = new int[100][100];
         for(int i=0;i<=m;i++)
             for(int j =0; j <= n; j++)
              Scanner scanner3 = new Scanner(System.in);
              int o = scanner3.nextInt();
             System.out.println();
         for(int i=0;i<=m;i++)
             for(int j =0; j <= n; j++)
              System.out.print(a[i][j] + "\t");
             System.out.println();
    }I am getting an output as this
    output:
    Enter the number of rows: 2
    Enter the number of coulmns:1
    The size of the matrix is : 2 x 1
    1
    2
    1
    2
    3
    5
    0     0     
    0     0     
    0     0     
    how should i assig those input values to my array..
    Please help

  • [Solved] 27.8.4 How to Create a VO on a REF CURSOR - Missing first row

    Searching the forum I found: BC4J - Get one less row from view object.
    Dive into BC4J related  --REF CURSOR (Resultset)
    The first message did not have any answers, and the second had a follow up question - still no answers though - and I thought I would try a different title.
    (This is off topic, but it would be a great help if the search results also displayed the number of replys in the thread. That way, I wouldn't have to view the messages that don't have responses.)
    (This will be deployed on a server that has the ADF for JDeveloper 10.1.2 installed, so using that version of JDeveloper to develop the app.)
    Okay, back to the problem ==>
    I created a VO from a ref cursor, using the manual as a guide. When I run a page that displays a read only table of the view object, I am missing the first row. (Always the first row!) I don't have any order set, and if I call the ref cursor in a Java program for testing, I see all rows and the count is correct.
    One other point, when I call the page, I get the following validation error:
    Validation Error
    You must correct the following error(s) before proceeding:
    * JBO-29000: Unexpected exception caught: java.lang.ClassCastException, msg=null
    * null
    I still see the table, it is just missing the first row of data.
    In my form I have first, previous set, next set , and last
    navigation buttons. If I press last then first, the error goes away. I still don't see the missing row though.
    Any guidance would be appreciated! I can post my code, but it is pretty much the same code in the AdvancedViewObjectExamples.zip in the ViewObjectOnRefCursor example. I just substituted my two package calls (getRefCursor and getRefCursorCount).
    Thanks, Ken

    Went back to a backup copy of the source. Fixed the error. Now I'm back to just not being able to see the first row of data.
    Additional Note: I had removed fields in the display. Once I truncated the ps_txn table in the schema defined by the model, the data would display (Still without the first record.)
    Are there any examples that are more in depth than the few pages in the developer guide?
    Here is the code for my VOImpl class:
    package newslinearchive.model.datamodel;
    import java.math.BigDecimal;
    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Timestamp;
    import java.sql.Types;
    import oracle.jbo.InvalidParamException;
    import oracle.jbo.JboException;
    import oracle.jbo.domain.Date;
    import oracle.jbo.domain.Number;
    import oracle.jbo.server.DBTransaction;
    import oracle.jbo.server.QueryCollection;
    import oracle.jbo.server.SQLBuilder;
    import oracle.jbo.server.ViewObjectImpl;
    import oracle.jbo.server.ViewRowImpl;
    import oracle.jbo.server.ViewRowSetImpl;
    import oracle.jdbc.driver.OracleCallableStatement;
    import oracle.jdbc.driver.OracleTypes;
    // --- File generated by Oracle ADF Business Components Design Time.
    // --- Custom code may be added to this class.
    // --- Warning: Do not modify method signatures of generated methods.
    public class SearchRefCursorImpl extends ViewObjectImpl {
    * This is the default constructor (do not remove)
    public SearchRefCursorImpl() {
    * Overridden framework method.
    * Executed when the framework needs to issue the database query for
    * the query collection based on this view object. One view object
    * can produce many related result sets, each potentially the result
    * of different bind variable values. If the rowset in query is involved
    * in a framework-coordinated master/detail viewlink, then the params array
    * will contain one or more framework-supplied bind parameters. If there
    * are any user-supplied bind parameter values, they will PRECEED the
    * framework-supplied bind variable values in the params array, and the
    * number of user parameters will be indicated by the value of the
    * numUserParams argument.
    protected void executeQueryForCollection(Object qc,Object[] params,int numUserParams) {
    storeNewResultSet(qc,retrieveRefCursor(qc,params));
    super.executeQueryForCollection(qc, params, numUserParams);
    * Overridden framework method.
    * Wipe out all traces of a built-in query for this VO
    protected void create() {
    getViewDef().setQuery(null);
    getViewDef().setSelectClause(null);
    setQuery(null);
    * Overridden framework method.
    * The role of this method is to "fetch", populate, and return a single row
    * from the datasource by calling createNewRowForCollection() and populating
    * its attributes using populateAttributeForRow().
    protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs) {
    * We ignore the JDBC ResultSet passed by the framework (null anyway) and
    * use the resultset that we've stored in the query-collection-private
    * user data storage
    rs = getResultSet(qc);
    * Create a new row to populate
    ViewRowImpl r = createNewRowForCollection(qc);
    try {
    * Populate new row by attribute slot number for current row in Result Set
    // populateAttributeForRow(r,0, rs.getLong(1));
    // populateAttributeForRow(r,1, rs.getString(2));
    // populateAttributeForRow(r,2, rs.getString(3));
    // MASTERID NOT NULL NUMBER
    populateAttributeForRow(r,0, rs.getBigDecimal(1));
    //ID NOT NULL NUMBER
    populateAttributeForRow(r,1, rs.getBigDecimal(2));
    // CAID NOT NULL NUMBER
    populateAttributeForRow(r,2, rs.getBigDecimal(3));
    // LANGUAGE NOT NULL VARCHAR2(30)
    populateAttributeForRow(r,3, rs.getString(4));
    // IS_CURRENT_VERSION NOT NULL NUMBER(1)
    populateAttributeForRow(r,4, rs.getBigDecimal(5));
    // FOLDER_ID NOT NULL NUMBER
    populateAttributeForRow(r,5, rs.getBigDecimal(6));
    // FOLDER_REGION_ID NOT NULL NUMBER
    populateAttributeForRow(r,6, rs.getBigDecimal(7));
    // NAME NOT NULL VARCHAR2(256)
    populateAttributeForRow(r,7, rs.getString(8));
    // DISPLAY_NAME VARCHAR2(256)
    populateAttributeForRow(r,8, rs.getString(9));
    // ITEMTYPE NOT NULL VARCHAR2(30)
    populateAttributeForRow(r,9, rs.getString(10));
    // SUBTYPE VARCHAR2(40)
    populateAttributeForRow(r,10, rs.getString(11));
    // SUBTYPE_CAID NUMBER
    populateAttributeForRow(r,11, rs.getBigDecimal(12));
    // PARENT_ITEM_ID NUMBER
    populateAttributeForRow(r,12, rs.getBigDecimal(13));
    // CATEGORY_ID NUMBER
    populateAttributeForRow(r,13, rs.getBigDecimal(14));
    // CATEGORY_CAID NUMBER
    populateAttributeForRow(r,14, rs.getBigDecimal(15));
    // AUTHOR VARCHAR2(50)
    populateAttributeForRow(r,15, rs.getString(16));
    // DESCRIPTION VARCHAR2(2000)
    populateAttributeForRow(r,16, rs.getString(17));
    // PUBLISH_DATE NOT NULL DATE
    populateAttributeForRow(r,17, rs.getDate(18));
    // EXPIREMODE VARCHAR2(90)
    populateAttributeForRow(r,18, rs.getString(19));
    // EXPIRENUMBER NUMBER
    populateAttributeForRow(r,19, rs.getBigDecimal(20));
    // EXPIREDATE DATE
    populateAttributeForRow(r,20, rs.getDate(21));
    // IMAGE VARCHAR2(350)
    populateAttributeForRow(r,21, rs.getString(22));
    // KEYWORDS VARCHAR2(2000)
    populateAttributeForRow(r,22, rs.getString(23));
    // URL VARCHAR2(4000)
    populateAttributeForRow(r,23, rs.getString(24));
    // FILENAME VARCHAR2(350)
    populateAttributeForRow(r,24, rs.getString(25));
    // TEXT CLOB()
    populateAttributeForRow(r,25, rs.getClob(26));
    // FOLDER_LINK_ID NUMBER
    populateAttributeForRow(r,26, rs.getBigDecimal(27));
    // FOLDER_LINK_CAID NUMBER
    populateAttributeForRow(r,27, rs.getBigDecimal(28));
    // ACTIVE NOT NULL NUMBER(1)
    populateAttributeForRow(r,28, rs.getBigDecimal(29));
    // CAN_BE_CHECKEDOUT NUMBER(1)
    populateAttributeForRow(r,29, rs.getBigDecimal(30));
    // IS_ITEM_CHECKEDOUT NUMBER(1)
    populateAttributeForRow(r,30, rs.getBigDecimal(31));
    // CHECKER_USERNAME VARCHAR2(256)
    populateAttributeForRow(r,31, rs.getString(32));
    // CHECKOUT_DATE DATE
    populateAttributeForRow(r,32, rs.getDate(33));
    // FULLSCREEN NOT NULL NUMBER(1)
    populateAttributeForRow(r,33, rs.getBigDecimal(34));
    // INPLACE NOT NULL NUMBER(1)
    populateAttributeForRow(r,34, rs.getBigDecimal(35));
    // CREATEDATE NOT NULL DATE
    populateAttributeForRow(r,35, rs.getDate(36));
    // CREATOR NOT NULL VARCHAR2(256)
    populateAttributeForRow(r,36, rs.getString(37));
    // UPDATEDATE DATE
    populateAttributeForRow(r,37, rs.getDate(38));
    // UPDATOR VARCHAR2(256)
    populateAttributeForRow(r,38, rs.getString(39));
    // SECURITY VARCHAR2(25)
    populateAttributeForRow(r,39, rs.getString(40));
    // VISIBLE NOT NULL NUMBER(1)
    populateAttributeForRow(r,40, rs.getBigDecimal(41));
    // SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,41, rs.getBigDecimal(42));
    // CATEGORY_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,42, rs.getBigDecimal(43));
    // AUTHOR_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,43, rs.getBigDecimal(44));
    // CREATE_DATE_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,44, rs.getBigDecimal(45));
    // ITEMTYPE_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,45, rs.getBigDecimal(46));
    catch (SQLException s) {
    throw new JboException(s);
    return r;
    * Overridden framework method.
    * Return true if the datasource has at least one more record to fetch.
    protected boolean hasNextForCollection(Object qc) {
    ResultSet rs = getResultSet(qc);
    boolean nextOne = false;
    try {
    nextOne = rs.next();
    * When were at the end of the result set, mark the query collection
    * as "FetchComplete".
    if (!nextOne) {
    setFetchCompleteForCollection(qc, true);
    * Close the result set, we're done with it
    rs.close();
    catch (SQLException s) {
    throw new JboException(s);
    return nextOne;
    * Overridden framework method.
    * The framework gives us a chance to clean up any resources related
    * to the datasource when a query collection is done being used.
    protected void releaseUserDataForCollection(Object qc, Object rs) {
    * Ignore the ResultSet passed in since we've created our own.
    * Fetch the ResultSet from the User-Data context instead
    ResultSet userDataRS = getResultSet(qc);
    if (userDataRS != null) {
    try {
    userDataRS.close();
    catch (SQLException s) {
    /* Ignore */
    super.releaseUserDataForCollection(qc, rs);
    * Overridden framework method
    * Return the number of rows that would be returned by executing
    * the query implied by the datasource. This gives the developer a
    * chance to perform a fast count of the rows that would be retrieved
    * if all rows were fetched from the database. In the default implementation
    * the framework will perform a SELECT COUNT(*) FROM (...) wrapper query
    * to let the database return the count. This count might only be an estimate
    * depending on how resource-intensive it would be to actually count the rows.
    public long getQueryHitCount(ViewRowSetImpl viewRowSet) {
    Long result = (Long)callStoredFunction(NUMBER,
    "PORTAL.SEARCH_REFCURSOR.getRefCursorCount",
    viewRowSet.getParameters(true));
    return result.longValue();
    // ------------- PRIVATE METHODS ----------------
    * Return a JDBC ResultSet representing the REF CURSOR return
    * value from our stored package function.
    * new Object[]{getNamedBindParamValue("Email",params)}
    private ResultSet retrieveRefCursor(Object qc, Object[] params) {
    ResultSet rs = (ResultSet)callStoredFunction(OracleTypes.CURSOR,
    "PORTAL.SEARCH_REFCURSOR.getRefCursor",
    null);
    return rs ;
    private Object getNamedBindParamValue(String varName, Object[] params) {
    Object result = null;
    if (getBindingStyle() == SQLBuilder.BINDING_STYLE_ORACLE_NAME) {
    if (params != null) {
    for (Object param : params) {
    Object[] nameValue = (Object[])param;
    String name = (String)nameValue[0];
    if (name.equals(varName)) {
    return (String)nameValue[1];
    throw new JboException("No bind variable named '"+varName+"'");
    * Store a new result set in the query-collection-private user-data context
    private void storeNewResultSet(Object qc, ResultSet rs) {
    ResultSet existingRs = getResultSet(qc);
    // If this query collection is getting reused, close out any previous rowset
    if (existingRs != null) {
    try {existingRs.close();} catch (SQLException s) {}
    setUserDataForCollection(qc,rs);
    hasNextForCollection(qc); // Prime the pump with the first row.
    * Retrieve the result set wrapper from the query-collection user-data
    private ResultSet getResultSet(Object qc) {
    return (ResultSet)getUserDataForCollection(qc);
    * Return either null or a new oracle.jbo.domain.Date
    private static Date nullOrNewDate(Timestamp t) {
    return t != null ? new Date(t) : null;
    * Return either null or a new oracle.jbo.domain.Number
    private static Number nullOrNewNumber(BigDecimal b) {
    try {
    return b != null ? new Number(b) : null;
    catch (SQLException s) { }
    return null;
    //----------------[ Begin Helper Code ]------------------------------
    public static int NUMBER = Types.NUMERIC;
    public static int DATE = Types.DATE;
    public static int VARCHAR2 = Types.VARCHAR;
    public static int CLOB = Types.CLOB;
    * Simplifies calling a stored function with bind variables
    * You can use the NUMBER, DATE, and VARCHAR2 constants in this
    * class to indicate the function return type for these three common types,
    * otherwise use one of the JDBC types in the java.sql.Types class.
    * NOTE: If you want to invoke a stored procedure without any bind variables
    * ==== then you can just use the basic getDBTransaction().executeCommand()
    * @param sqlReturnType JDBC datatype constant of function return value
    * @param stmt stored function statement
    * @param bindVars Object array of parameters
    * @return function return value as an Object
    protected Object callStoredFunction(int sqlReturnType, String stmt,
    Object[] bindVars) {
    CallableStatement st = null;
    try {
    st = getDBTransaction().createCallableStatement("begin ? := " + stmt +
    "; end;", 0);
    st.registerOutParameter(1, sqlReturnType);
    if (bindVars != null) {
    for (int z = 0; z < bindVars.length; z++) {
    st.setObject(z + 2, bindVars[z]);
    st.executeUpdate();
    return st.getObject(1);
    catch (SQLException e) {
    throw new JboException(e);
    finally {
    if (st != null) {
    try {
    st.close();
    catch (SQLException e) {}
    /**Gets the bind variable value for Email
    public String getEmail() {
    return (String)getNamedWhereClauseParam("Email");
    /**Sets <code>value</code> for bind variable Email
    public void setEmail(String value) {
    setNamedWhereClauseParam("Email", value);
    /**getEstimatedRowCount - overridden for custom java data source support.
    public long getEstimatedRowCount() {
    long value = super.getEstimatedRowCount();
    return value;
    Thanks, Ken

  • How to put a collection into a Ref Cursor?

    Hi,
    I am trying to create a procedure (inside a package) which fills a collection and I need to fill a ref cursor (out parameter) with this collection. I can fill the collection but I how can I fill the ref cursor? I am receiving the message "PL/SQL: ORA-00902: invalid datatype" (Highlighted below as comments)
    I have a limitation: I am not allowed to create any kind of objects at the database schema level, so I have to create them inside the package. I'm writting it with SQL Tools 1.4, I'm also not allowed to do this in SQL+.
    This is the code of the package. The cursors' selects were simplified just because they are not the problem, but their structure is like follows below.
    CREATE OR REPLACE PACKAGE U3.PKG_TESTE AS
    TYPE REC_TYPE IS RECORD(
    COL1 VARCHAR2(50) ,
    COL2 VARCHAR2(100) ,
    COL3 VARCHAR2(20) ,
    COL4 VARCHAR2(30) ,
    COL5 VARCHAR2(100) ,
    COL6 VARCHAR2(50) ,
    COL7 NUMBER(3) ,
    COL8 VARCHAR2(30) ,
    COL9 VARCHAR2(16) ,
    COL10 VARCHAR2(50) ,
    COL11 NUMBER(4) ,
    COL12 VARCHAR2(40)
    TYPE REC_TYPE_LIST IS TABLE OF REC_TYPE
    INDEX BY BINARY_INTEGER;
    TYPE C_RESULTSET IS REF CURSOR;
    VAR_TAB_TESTE     REC_TYPE_LIST;
    PROCEDURE     Z_REC_INSTANCE
    pUSER_SYS_CODE VARCHAR2,
    pSYS_SEG_CODE VARCHAR2,
    pComplFiltro VARCHAR2,
    pCodInter NUMBER,
    cResultset out C_RESULTSET
    END PKG_TESTE ;
    CREATE OR REPLACE PACKAGE BODY U3.PKG_TESTE
    AS
    PROCEDURE Z_REC_INSTANCE
    pUSER_SYS_CODE varchar2,
    pSYS_SEG_CODE varchar2,
    pComplFiltro varchar2,
    pCodInter number
    AS
    cursor cur1 is
    select 'A' COL1, 'B' COL2, 'C' COL3, 'D' COL4, 'E' COL5,
    'F' COL6, 'G' COL7, 'H' COL8
    FROM DUAL;
    regCur1 cur1%rowtype;
    cursor cur2 is
    SELECT 'I' C1, 'J' C2, 'K' C3, 'L' C4
    FROM DUAL;
    regCur2 cur2%rowtype;
    varSQL varchar2(4000);
    varCOL10s varchar2(100);
    varFiltroAtrib varchar2(100);
    varCount number(10);
    BEGIN
    varCount := 1;
    open cur1;
    Loop
    fetch cur1 into regCur1;
    exit when cur1%notfound;
    open cur2;
    Loop
    fetch cur2 into regCur2;
    exit when cur2%notfound;
    VAR_TAB_TESTE(varCount).COL1 := regCur1.COL1;
    VAR_TAB_TESTE(varCount).COL2 := regCur1.COL2;
    VAR_TAB_TESTE(varCount).COL3 := regCur1.COL3;
    VAR_TAB_TESTE(varCount).COL4 := regCur1.COL4;
    VAR_TAB_TESTE(varCount).COL5 := regCur1.COL5;
    VAR_TAB_TESTE(varCount).COL6 := regCur1.COL6;
    VAR_TAB_TESTE(varCount).COL7 := regCur1.COL7;
    VAR_TAB_TESTE(varCount).COL8 := regCur1.COL8;
    VAR_TAB_TESTE(varCount).COL9 := regCur2.C1;
    VAR_TAB_TESTE(varCount).COL10 := regCur2.C2;
    VAR_TAB_TESTE(varCount).COL11 := regCur2.C3;
    VAR_TAB_TESTE(varCount).COL12 := regCur2.C4;
    varCount := varCount + 1;
    end Loop;
    end Loop;
    -- I'd like to do something like this:
    -- c_resultset := select * from var_tab_teste;
    -- but i don't know how to put the records of the type on the ref cursor,
    -- probably because I don't know how to select them
    -- pl/sql: ora-00902: invalid datatype
    for varCount in (select COL1 from table( CAST ( VAR_TAB_TESTE AS REC_TYPE_LIST ) ))
    loop
    dbms_output.put('WORKS');
    end loop;
    END Z_REC_INSTANCE;
    END PKG_TESTE;
    SHOW     ERR     PACKAGE          PKG_TESTE;
    SHOW     ERR     PACKAGE BODY     PKG_TESTE;
    SHOW     ERR     PROCEDURE     PKG_TESTE.Z_REC_INSTANCE;
    I'm using:
    Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    Thanks in advance.

    I don't have the exact version but in 9iOK I lied, I found a 9i instance ;-)
    Oracle9i Enterprise Edition Release 9.2.0.7.0 - 64bit Production
    JServer Release 9.2.0.7.0 - Production
    SQL> CREATE TABLE table_name (column_name VARCHAR2 (30));
    Table created.
    SQL> INSERT INTO table_name VALUES ('value one');
    1 row created.
    SQL> INSERT INTO table_name VALUES ('value two');
    1 row created.
    SQL> COMMIT;
    Commit complete.
    SQL> CREATE OR REPLACE PACKAGE package_name
      2  AS
      3     TYPE collection_type_name IS TABLE OF table_name%ROWTYPE;
      4
      5     FUNCTION function_name
      6        RETURN collection_type_name PIPELINED;
      7  END package_name;
      8  /
    Package created.
    SQL> CREATE OR REPLACE PACKAGE BODY package_name
      2  AS
      3     FUNCTION function_name
      4        RETURN collection_type_name PIPELINED
      5     IS
      6     BEGIN
      7        FOR record_name IN (SELECT column_name
      8                            FROM   table_name) LOOP
      9           PIPE ROW (record_name);
    10        END LOOP;
    11
    12        RETURN;
    13     END function_name;
    14  END package_name;
    15  /
    Package body created.
    SQL> VARIABLE variable_name REFCURSOR;
    SQL> BEGIN
      2     OPEN :variable_name FOR
      3        SELECT column_name
      4        FROM   TABLE (package_name.function_name);
      5  END;
      6  /
    PL/SQL procedure successfully completed.
    SQL> PRINT variable_name;
    COLUMN_NAME
    value one
    value two
    SQL>I recommend though that you test this thoroughly. There were bugs with this approach when it was newly introduced that prevented you from dropping the package.

  • How to find number of files in a folder using pl/sql

    please someone guide as to how to find number of files in a folder using pl/sql
    Regards

    The Java option works well.
    -- results table that will contain a file list result
    create global temporary table directory_list
            directory       varchar2(1000),
            filename        varchar2(1000)
    on commit preserve rows
    -- allowing public access to this temp table
    grant select, update, insert, delete on directory_list to public;
    create or replace public synonym directory_list for directory_list;
    -- creating the java proc that does the file listing
    create or replace and compile java source named "ListFiles" as
    import java.io.*;
    import java.sql.*;
    public class ListFiles
            public static void getList(String directory, String filter)
            throws SQLException
                    File path = new File( directory );
                    final String ExpressionFilter =  filter;
                    FilenameFilter fileFilter = new FilenameFilter() {
                            public boolean accept(File dir, String name) {
                                    if(name.equalsIgnoreCase(ExpressionFilter))
                                            return true;
                                    if(name.matches("." + ExpressionFilter))
                                            return true;
                                    return false;
                    String[] list = path.list(fileFilter);
                    String element;
                    for(int i = 0; i < list.length; i++)
                            element = list;
    #sql {
    insert
    into directory_list
    ( directory, filename )
    values
    ( :directory, :element )
    -- creating the PL/SQL wrapper for the java proc
    create or replace procedure ListFiles( cDirectory in varchar2, cFilter in varchar2 )
    as language java
    name 'ListFiles.getList( java.lang.String, java.lang.String )';
    -- punching a hole in the Java VM that allows access to the server's file
    -- systems from inside the Oracle JVM (these also allows executing command
    -- line and external programs)
    -- NOTE: this hole MUST be secured using proper Oracle security (e.g. AUTHID
    -- DEFINER PL/SQL code that is trusted)
    declare
    SCHEMA varchar2(30) := USER;
    begin
    dbms_java.grant_permission(
    SCHEMA,
    'SYS:java.io.FilePermission',
    '<<ALL FILES>>',
    'execute, read, write, delete'
    dbms_java.grant_permission(
    SCHEMA,
    'SYS:java.lang.RuntimePermission',
    'writeFileDescriptor',
    dbms_java.grant_permission(
    SCHEMA,
    'SYS:java.lang.RuntimePermission',
    'readFileDescriptor',
    commit;
    end;
    To use:
    SQL> exec ListFiles('/tmp', '*.log' );
    PL/SQL procedure successfully completed.
    SQL> select * from directory_list;
    DIRECTORY FILENAME
    /tmp X11_newfonts.log
    /tmp ipv6agt.crashlog
    /tmp dtappint.log
    /tmp Core.sd-log
    /tmp core_intg.sd-log
    /tmp da.sd-log
    /tmp dhcpclient.log
    /tmp oracle8.sd-log
    /tmp cc.sd-log
    /tmp oms.log
    /tmp OmniBack.sd-log
    /tmp DPISInstall.sd-log
    12 rows selected.
    SQL>

  • Want to manipulate the ref cursor

    Hi,
    iam having a procedure whiuch returns a ref cursor as a output parameter having 20 columns.
    i had to manipulate only 2 columns in that ref cursor output in another calling procedure.
    iam getting an error when iam fetching the ref cursor result into only 2 variables.
    How can i achieve this ?

    Why?
    Let's see it ->
    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:00.18
    satyaki>
    satyaki>create or replace procedure r_gen_arg(
      2                                         choice in number,
      3                                         b in out sys_refcursor
      4                                       )
      5  is  
      6    str   varchar2(500);
      7  begin   
      8    if choice = 1 then      
      9        str := 'select * from emp';   
    10    elsif choice = 2 then      
    11      str := 'select * from dept';   
    12    end if;       
    13   
    14    open b for str;
    15  exception  
    16    when others then     
    17      dbms_output.put_line(sqlerrm);
    18  end;
    19  /
    Procedure created.
    Elapsed: 00:00:04.51
    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    r_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     r_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.85
    satyaki>
    satyaki>Here, i don't have to use separate variable to hold those required value.
    Regards.
    Satyaki De.

  • Ref cursors and dynamic sql..

    I want to be able to use a fuction that will dynamically create a SQL statement and then open a cursor based on that SQL statement and return a ref to that cursor. To achieve that, I am trying to build the sql statement in a varchar2 variable and using that variable to open the ref cursor as in,
    open l_stmt for refcurType;
    where refcurType is a strong ref cursor. I am unable to do so because I get an error indication that I can not use strong ref cursor type. But, if I can not use a strong ref cursor, I will not be able to use it to build the report based on the ref cursor because Reports 9i requires strong ref cursors to be used. Does that mean I can not use dynamic sql with Reports 9i ref cursors? Else, how I can do that? Any documentation available?

    Philipp,
    Thank you for your reply. My requirement is that, sometimes I need to construct a whole query based on some input, and sometimes not. But the output record set would be same and the layout would be more or less same. I thought ref cursor would be ideal. Ofcourse, I could do this without dynamic SQL by writing the SQL multiple times if needed. But, I think dynamic SQL is a proper candidate for this case. Your suggestion to use lexical variable is indeed a good alternative. In effect, if needed, I could generate an entire SQL statement and place in some place holder (like &stmt) and use it as a static SQL query in my data model. In that case, why would one ever need ref cursor in reports? Is one more efficient over the other? My guess is, in the lexical variable case, part of the processing (like parsing) is done on the app server while in a function based ref cursor, the entire process takes place in the DB server and there is probably a better chance for re-use(?)
    Thanks,
    Murali.

  • Report using ref cursor or dynamic Sql

    Hi,
    I never create a report using a ref cursor or a dynamic sql. Could any one help me to solve the below issue.
    I have 2 tables.
    1. Student_Record
    2. Student_csv_help
    Student_Record the main table where the data is stored.
    Student_csv_help will contain the all the column names of the Student_record.
    CREATE TABLE Student_CSV_HELP
    ENTRY_ID NUMBER,
    RAW_NAME VARCHAR2(40 BYTE),
    DESC_NAME VARCHAR2(1000 BYTE),
    IN_OUTPUT_LIST VARCHAR2(1 BYTE)
    SET DEFINE OFF;
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (1, 'S_ID', 'Student ID', 'Y');
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (2, 'S_Name', 'Student Name', 'Y');
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (3, 'S_Join_date', 'Joining Date', 'Y');
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (4, 'S_Address', 'Address', 'Y');
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (5, 'S_Fee', 'Tution Fee', 'N');
    commit;
    CREATE TABLE Student_record
    S_ID NUMBER,
    S_Name VARCHAR2(100 BYTE),
    S_Join_date date,
    S_Address VARCHAR2(360 BYTE),
    S_Fee Number
    Insert into Student_record
    (S_ID, S_Name, S_Join_date, S_Address,S_Fee)
    Values
    (101, 'john', TO_DATE('12/17/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94777', 2000);
    Insert into Student_record
    (S_ID, S_Name, S_Join_date, S_Address,S_Fee)
    Values
    (102, 'arif', TO_DATE('12/18/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94444', 3000);
    Insert into Student_record
    (S_ID, S_Name, S_Join_date, S_Address,S_Fee)
    Values
    (103, 'raj', TO_DATE('12/19/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94555', 2500);
    Insert into Student_record
    (S_ID, S_Name, S_Join_date, S_Address,S_Fee)
    Values
    (104, 'singh', TO_DATE('12/20/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94666', 2000);
    Commit;
    Now my requirement is:
    I have a form with Student_record data block. When i Click on print Button on this form. It will open another window which has Student_CSV_HELP.DESC_NAME and a check box before this.
    The window look like as below:
    check_box       DESC_NAME+
    X                   S_ID+
    --                   S_Name+
    X                   S_Join_date+
    X                   S_Address+
    --                  S_Fee+
    X  means check box checked.+
    --  means check box Unchecked.+
    After i selected these check boxes i will send 2 parameters to the report server
    1. a string parameter to the report server which has the value 'S_ID,S_Join_date,S_Address' (p_column_name := 'S_ID,S_Join_date,S_Address');
    2. the s_id value from the student_record block (p_S_id := '101');
    Now my requirement is when i click on run. I need a report like as below:
    Student ID : 101+
    Joining Date : 12/17/2009 08:00:00+
    Address : CA-94777+
    This is nothing but the ref cursor should run like as below:
    Select S_id from student_record block S_id = :p_S_id;
    Select S_Join_date from student_record block S_id = :p_S_id;
    Select S_Address from student_record block S_id = :p_S_id;
    So, according to my understanding i have to select the columns at the run time. I dont have much knowledge in creating reports using ref cursor or dynamic sql.
    So please help me to solve this issue.
    Thanks in advance.

    Plain sql should satisfy your need. Try ....
    Select S_id, S_Join_date, S_Address
    from student_record
    where S_id = :p_S_id

  • Ref cursor and dynamic sql

    Hi..
    I'm using a ref cursor query to fetch data for a report and works just fine. However i need to use dynamic sql in the query because the columns used in the where condition and for some calculations may change dynamically according to user input from the form that launches the report..
    Ideally the query should look like this:
    select
    a,b,c
    from table
    where :x = something
    and :y = something
    and (abs(:x/:y........)
    The user should be able to switch between :x and :y
    Is there a way to embed dynamic sql in a ref cursor query in Reports 6i?
    Reports 6i
    Forms 6i
    Windows 2000 PRO

    Hello Nicola,
    You can parameterize your ref cursor by putting the query's select statement in a procedure/function (defined in your report, or in the database), and populating it based on arguments accepted by the procedure.
    For example, the following procedure accepts a strongly typed ref cursor and populates it with emp table data based on the value of the 'mydept' input parameter:
    Procedure emp_refcursor(emp_data IN OUT emp_rc, mydept number) as
    Begin
    -- Open emp_data for select all columns from emp where deptno = mydept;
    Open emp_data for select * from emp where deptno = mydept;
    End;
    This procedure/function can then be called from the ref cursor query program unit defined in your report's data model, to return the filled ref cursor to Reports.
    Thanks,
    The Oracle Reports Team.

Maybe you are looking for

  • How to autopopulate fields in a portal form based on database procedure?

    Dear gurus, I am a newbie to the portal world and i have a rather unique problem. I have searched online but still cant find a solution to my problem. I have a portal form (AS version 10.1.4) based on a db procedure that accepts only one parameter. T

  • Customer Ageing query

    Hi We have a standard query in BW for customer ageing query 0FIAR_C03_Q0002. In this query we have several dates 1. Document date 2. Posting date 3. Base line date 4. Net due date. Its very tough to understand what is the significance of these dates

  • JRC - multiple tables in crystal report

    Post Author: Crystal Wong CA Forum: JAVA Hi, I am using the Java Reporting component of Crystal Report XI R2 SP2. I encounter error when pushing 2 Java resultset to a report as a datasource, like the code belows, ReportClientDocument reportClientDoc

  • Thunderbolt has stopped working with macbook pro

    Thunderbolt display paired to macbook pro and working fine. Turned off Macbook to go portable.  When returned home plugged n Thunderbolt to Mac - there is no activity at all on Thunderbolt display.  No changes to set up were made. Any suggestions?

  • C compiler cannot create executables on fresh install

    This has happened to me twice now on this laptop. Straight after installing my system and the packages from my saved cache, I try to build a few of my AUR packages, only to be told that the compiler can't create executables. Somehow I fixed it the la