Cannot get OUT parameter from stored procedure

Hi,
I am new to stored procedure programming. I wrote a simple java stored procedure as follows:
package fvt;
import java.sql.*;
import java.io.*;
public class FVTProcedures
extends COM.ibm.db2.app.StoredProc {
public void addRecord(int id, String name, int status)
throws SQLException {
java.sql.Statement stmt = null;
java.sql.Connection con = null;
PrintWriter pw = null;
try {
status =3;
pw = new PrintWriter(new FileWriter("c:/temp/fvtproc.txt"));
pw.println("starting...");
// get connection
con =getConnection();
pw.println("Got connection");
stmt = con.createStatement();
stmt.execute("INSERT INTO cmtest (id, name) values (" + id + ",'"+name+"')");
pw.println("Inserted the record");
if (!con.getAutoCommit()) {
con.commit();
pw.println("Committed the connection");
catch (SQLException sqle) {
pw.println(sqle.getMessage());
catch (Exception e) {
pw.println(e.getMessage());
finally {
status =2;
pw.close();
try {
if (stmt != null) {
stmt.close();
catch (SQLException sqle) {}
try {
if (con != null) {
con.close();
catch (SQLException sqle) {}
Then I use the following sql command to create this stored procedure, especially register status as OUT parameter.
CREATE PROCEDURE addRecord (IN id INT, IN name VARCHAR(20), OUT status INTEGER)
FENCED LANGUAGE JAVA EXTERNAL NAME 'fvt.FVTProcedures!addRecord' PARAMETER
STYLE DB2GENERAL
My java program calling this stored proc is as follows:
import java.sql.*;
import javax.sql.*;
public class CallableStmtTest {
     COM.ibm.db2.jdbc.DB2ConnectionPoolDataSource ds = null;
     public static void main(String args[]) {
          CallableStmtTest dt = new CallableStmtTest();
          try {
               dt.test();
          } catch (Exception e) {
               e.printStackTrace(System.out);
     public CallableStmtTest() {
          ds = new COM.ibm.db2.jdbc.DB2ConnectionPoolDataSource();
          ds.setUser("username");
          ds.setPassword("password");
          ds.setDatabaseName("database");
public void test() {
java.sql.Connection conn = null;
CallableStatement cs = null;
String sql = "CALL ADDRECORD(?, ?, ?)" ;
try {
conn = ds.getPooledConnection().getConnection();
conn.setAutoCommit(false);
System.out.println("Got the connection");
cs = conn.prepareCall( sql ) ; /* con is the connection */
System.out.println("Callable statement is prepared");
cs.registerOutParameter(3, java.sql.Types.INTEGER);
cs.setInt(1, 1001 );
cs.setString(2, "1001");
cs.execute() ;
System.out.println("Callable statement is executed, return status: "+cs.getInt(3));
conn.commit();
catch(SQLException sqle) {
sqle.printStackTrace();
finally {
try {
if (cs!=null) {cs.close();}
catch (SQLException sqle1) {
try {
if (conn!=null) {conn.close();}
catch (SQLException sqle1) {
However, the out put is always
Callable statement is executed, return status: 0
while i expect to be
Callable statement is executed, return status: 2
Can anyone tell me what's wrong with that?
thansk,
JST

public void addRecord(int id, String name, int status)
throws SQLException {
status =3;In regular java you are never going to see this value (3) outside of that method. Java doesn't work that way.
So unless java inside the DB works really differently from regular java, you are going to have to pass something else.

Similar Messages

  • Get out values from stored procedure

    Hi folks,
    I have need of an aid. I have created this stored procedure:
    CREATE OR REPLACE PROCEDURE ProceduraDiProva (
    p_val1 IN NUMBER DEFAULT 1,
    p_val2 IN NUMBER DEFAULT 1,
    p_val3 OUT NUMBER,
    p_val4 OUT NUMBER)
    AS
    BEGIN
    p_val3 := p_val1 + p_val2;
    p_val4 := 999;
    END ProceduraDiProva;
    I call the procedure into shell script
    $ORACLE_HOME/bin/sqlplus -s user/pwd@oracleid > oracle.log << END
    spool ciccio.txt
    declare
    var a_out number;
    var b_out number;
    begin
    var a_out:=0;
    exec ProceduraDiProva(1, 2, a_out, b_out);
    end;
    spool off;
    exit
    END
    I would know as I make to insert 'a_out' and 'b_out' in a shell variables
    Tanks in advance

    I found an example with windows
    Create a file cmd with;
    FOR /F "usebackq delims=!" %%i IN (`sqlplus -s %usuario%/%pwd%@%ddbb% @1.sql`) DO set xresult=%%i
    echo %xresult%
    And the 1.sql:
    set timing off
    set feedback off
    set pages 0
    select sysdate from dual;
    exit
    ------------------------------------------------------------------------------------------

  • Triggers accepting parametes from stored procedures

    Can triggers accept parameters from stored procedures like some filename or column name of a table and pass them to external c procedures.If so I would greatly appreciate if any one could provide me with an example.
    P.S The trigger is on a view and the view which in turn should be created in the stored procedure.
    Thanks
    Harini

    Hello,
    Yes you can invoke Web Services from the database, it is often called "Database Web Service call out" and it is documented in the Web Services Developer Guide
    Regards
    Tugdual Grall

  • Datetime parameter from stored procedure

    <p>I have a report written in CR10 which uses a stored procedure as the datasource. The stored procedure has 3 input parameters, two of which are datetime data types. When the crystal report is run, it prompts the user for the 3 parameters & runs just fine except...</p><p>For the date parameters, it prompts the user to enter a time as well. In previous versions of Crystal, parameters that were datetime data types in the stored procedure were just prompted for the date when the calling crystal report was run.</p><p>I attempted to edit the parameters in the report, but the "Value Type" is grayed out (I assume since the parameter is associated with the stored procedure, rather than being a user defined parameter within the report).  These date parameters are used in a BETWEEN statement in the stored proc, so if the user just enters a date but accepts the default time, the returned data gets flakey due to the addition of the time value passed by the parameter.</p><p> I tried setting a default value for the time, but I have to enter a date along with the time, which the report then uses as the default. The user then has to uncheck the "Pick from defaults" checkbox in order to enter their own date. This is really unwieldly for the end user, especially when they were previously able to just enter a date and not have to be concerned with a time at all.</p><p>Does anyone have suggestions on working around this issue? </p><p>Thanks in advance...</p>

    <p>You mention that you are using CRW version 10 for this.  What&#39;s the data source you are reporting against (you mention a stored procedure - but are you running against Oracle, SQL Server, DB2?).  Are you connecting natively or using ODBC? <br /></p>

  • How to get return values from stored procedure to ssis packge?

    Hi,
    I need returnn values from my stored procedure to ssis package -
    My procedure look like  and ssis package .Kindly help me to oget returnn value to my ssis package
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author: <Author,,Name>
    -- Create date: <Create Date,,>
    -- Description: <Description,,>
    -- =============================================
    ALTER PROCEDURE [TSC]
    -- Add the parameters for the stored procedure here
    @P_STAGE VARCHAR(2000)
    AS
    BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    -- Insert statements for procedure here
    --SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
    truncate table [INPUTS];
    INSERT
    INTO
    [INPUTS_BASE]
    SELECT
    [COLUMN]
    FROM [INPUTS];
    RETURN
    END
    and i am trying to get the return value from execute sql task and shown below
    and i am taking my returnn value to result set variable

    You need to have either OUTPUT parameters or use RETURN statement to return a value in stored procedures. RETURN can only return integer values whereas OUTPUT parameters can be of any type
    First modify your procedure to define return value or OUTPUT parameter based on requirement
    for details see
    http://www.sqlteam.com/article/stored-procedures-returning-data
    Once that is done in SSIS call sp from Execute SQL Task and in parameter mapping tabe shown above add required parameters and map them to variables created in SSIS and select Direction as Output or Return Value based on what option you used in your
    procedure.
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Getting result set from stored procedures in database controls in weblogic

    I am calling a stored procedure from database control which actually returns a result set
    when i call the stored procedure like
    * @jc:sql statement="call PROC4()"
    ResultSet sampleProc() throws SQLException;
    it gives me exception saying
    "weblogic.jws.control.ControlException: Method sampleProc is DML but does not return void or int"
    I would appreciate any help
    Thanks,
    Uma

    Thanks for you reply!
    1) The stored procedure has head
    CREATE OR REPLACE PROCEDURE X_OWNER.DISPLAY_ADDRESS
    cv_1 IN OUT SYS_REFCURSOR
    AS
    err_msg VARCHAR2(100);
    BEGIN
    --Adaptive Server has expanded all '*' elements in the following statement
    OPEN cv_1 FOR
    Select ...
    commit;
    EXCEPTION
    WHEN OTHERS THEN
    err_msg := SQLERRM;
    dbms_output.put_line (err_msg);
    ROLLBACK;
    END;
    If I only run select .. in DBArtisan, it display all 2030,000 rows in 3:44 minutes
    2) But when call stored procedure, it will take 80-100 minutes .
    3) The stored procedure is translated from sybase using migration tools, it's very simple, in sybase it just
    CREATE PROCEDURE X_OWNER.DISPLAY_ADDRESS
    AS
    BEGIN
    select ..
    The select part is exact same.
    4) The perl code is almost exact same, except the query sql:
    sybase verson: my $sql ="exec DISPLAY_ADDRESS";
    and no need bind the cursor parameter.
    This is batch job, we create a file with all information, and ftp to clients everynight.
    Thanks!
    Rulin

  • How to get a resultset from Stored Procedures

    How to efficiently and portably get resultsets from Oracle stored procedures? Oracle does not seem to follow JDBC standards here. A standard way in Oracle is to use a ref cursor and call getObject() on CallableStatement. However, Oracle seems to get all the data in the resultset in getObject(), which is inefficient and leads to large memory usage when the resultset is large.
    Another way in Oracle is to use getCursor() on an OracleCallableStatement, which is efficient but not portable across different application servers. For example, in WebSphere, this OracleCallableStatement is not available if we want WebSphere to manager the datasource.
    Any ideas will be greatly appreciated. Please email to [email protected]

    Oracle JDBC did not support return a result set, if you are using Oracle 9i, you can use pipeline function, then using the TABLE() function the get the row.
    Good Luck.
    Welcome to http://www.anysql.net/en/

  • Can we get data return from stored procedure in a select query ?

    Hello,
    Suppose i have a function GetSum(x,y) that returns sum of two numbers x and y .We can call this function from within a sql function like this :
    select GetSum(4,5) SUM from dual;But is this possible through a stored procedure ? i.e., can i call a stored procedure from within a select query like i have done in above code ?

    Hi,
    bootstrap wrote:
    Hello,
    Suppose i have a function GetSum(x,y) that returns sum of two numbers x and y .We can call this function from within a sql function like this :
    select GetSum(4,5) SUM from dual;But is this possible through a stored procedure ? i.e., can i call a stored procedure from within a select query like i have done in above code ?The short answer has already been given.
    Why can't you use a function?
    Suppose you could use a procedure. What results would you want to see from:
    SELECT  my_proc (4, 5)
    FROM    dual
    ;? Why?
    Explain what you want to do, and somebody will help you find a good way to do it.

  • Cannot get the parameter from a HTML page at the first time

    Hi everyone,
    I have a html page with <input name="username" ...>, and the submit action is a url to my JSF web application. In the start page of the JSF webapp, I use following code to get value of username.
    FacesContext facesContext = javax.faces.context.FacesContext.getCurrentInstance();
    String userName = (String)facesContext.getExternalContext().getRequestParameterMap().get("username");
    However, I cannot get it at the first time. The strange thing is if i click "refresh" button, the value of username is shown up on my page.
    Why? and How to solve it?
    Thanks in advance,

    Hi,
    Are you putting this code in the public void preprocess() method?
    Check out
    http://developers.sun.com/prodtech/javatools/jscreator/reference/techart/2/app_model.html
    The assumption is that Creator is being used.

  • How do i handle out parameter from a stored procedure in a vb form?

    hi all,
    I want to return a varchar2(500) type of out parameter from a pl/sql stored procedure to a vb form?? how do i do this??
    regards
    akshay

    Well, when you create the parameter collection for your command object, just set the correct value for the direction component.
    You would set it to one of the below, depending on if the parameter is IN OUT or only OUT:
            <parameter_obj>.Direction = ParameterDirectionEnum.adParamInputOutput
            <parameter_obj>.Direction = ParameterDirectionEnum.adParamOutput

  • Problems getting a resultset out of a stored procedure

    We're having a problem getting a resultset out of a stored procedure with JDBC. The third parameter for the procedure is an out REF CURSOR. Connection to the database is fine, we just keep getting the following error when we do the GetCursor(3) statement:
    ORA-00942: table or view does not exist
    We know for definate that something is coming out of the database as we can call it from ODBC without any errors. If anyone's got any ideas as to what's going wrong please let me know!
    The cut-down code follows:
    public class JSMatt extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    PrintWriter out = resp.getWriter();
    // Load the Oracle JDBC driver
    out.println("Registering driver...");
    Class.forName("oracle.jdbc.driver.OracleDriver");
    // Connect to the DB
    out.println("Connecting to database...");
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@computer:db",
    "username", "password");
    // Create a statement using a stored procedure
    out.println("Creating query...");
    OracleCallableStatement st = (OracleCallableStatement)conn.prepareCall ("BEGIN archive.spSrchLanguage (?, ?, ?); END;");
    st.registerOutParameter(3, OracleTypes.CURSOR);
    st.setInt(1, 0);
    st.setInt(2, 12);
    st.execute();
    ResultSet rs = ((OracleCallableStatement)st).getCursor(3);
    null

    Further study of my colleagues issue reveals that the problem only occurs where we are using a synonym for our package even though the user has permissions to run it (and indeed does when using ODBC or OLEDB).
    If we call a procedure in our package which does not return a ref cursor then the procedure is getting called fine (as can be evidenced by the database inserts etc within the procedures).
    Ideally we would like to use a synonym (I like to keep nice clean tidy schemas!) so if anyone knows how to get around it please let us know.
    Regards
    Jason.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Matthew Butt ([email protected]):
    We're having a problem getting a resultset out of a stored procedure with JDBC. The third parameter for the procedure is an out REF CURSOR. Connection to the database is fine, we just keep getting the following error when we do the GetCursor(3) statement:
    ORA-00942: table or view does not exist
    We know for definate that something is coming out of the database as we can call it from ODBC without any errors. If anyone's got any ideas as to what's going wrong please let me know!
    The cut-down code follows:
    public class JSMatt extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    PrintWriter out = resp.getWriter();
    // Load the Oracle JDBC driver
    out.println("Registering driver...");
    Class.forName("oracle.jdbc.driver.OracleDriver");
    // Connect to the DB
    out.println("Connecting to database...");
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@computer:db",
    "username", "password");
    // Create a statement using a stored procedure
    out.println("Creating query...");
    OracleCallableStatement st = (OracleCallableStatement)conn.prepareCall ("BEGIN archive.spSrchLanguage (?, ?, ?); END;");
    st.registerOutParameter(3, OracleTypes.CURSOR);
    st.setInt(1, 0);
    st.setInt(2, 12);
    st.execute();
    ResultSet rs = ((OracleCallableStatement)st).getCursor(3);
    <HR></BLOCKQUOTE>
    null

  • How to get RECORD data in output parameter of stored procedure

    I would like to return some data through RECORD structure from stored procedure.
    I have defined the RECORD as below:
    type ShipmentStatus is record(
    Booked integer,
    OnWater integer,
    OnRoad integer,
    InAir integer,
    OnRail integer,
    InWarehouse integer,
    Idle integer);
    the stored procedure is defined as
    create or replace procedure SP_MC_GET_SHIPMENT_STATUS
    iCustId in nvarchar2,
    oResult out ShipmentStatus
    I can get result in Sql*plus or PL/SQL developer, but I failed in get the result in Toplink.
    How can I get the output result, and convert it to an ENTITY by Toplink?
    Could you give me some advices on how to do mapping, how to call the stored procedure etc.., or code snip?
    Your answer is deeply appreciated. :)

    I'm not sure it is possible to get the PL/SQL record type through JDBC. Please try to access this procedure through JDBC to see if it is possible.
    You may need to convert the record type, to an object-type, i.e. wrap the procedure in another procedure that converts the record type. You could also just wrap the procedure in another that expands the record values into individual output parameters.

  • Length of "out char" parameter in stored procedure

    I call a SP with an output char parameter, the type is defined as a field in a table -- char(3),
    but when calling from stored procedure, it throws an exception:
    "ORA-01406: fetched column value was truncated"
    the exception happens in line 4:
    1. stmt->setSQL("call OUTPUT_CHAR1(:1)");
    2. stmt->registerOutParam(1, OCCISTRING, 10);          
    3. stmt->execute();
    4. string result = stmt->getString(1);
    One interesting thing is: if I use the same type as function return value(not output parameter), it works.
    Friends, please give me some idea..

    Just before commending about anyone it is good idea to go through Oracle Documentation .
    Go through the following link
    http://www.orafaq.com/faq/what_is_the_difference_between_varchar_varchar2_and_char_data_types
    and
    http://ora-01406.ora-code.com/ also
    Basic difference is CHAR is fixed length and VARCHAR2 variable length which takes more buffer than a fixed length since the length is also stored.
    Your error 'ORA-01406' is a common one in any place holder which does not have space to hold enough data. Thats why I told you to change to Varchar2 which is common fix in this case where exact data is not send to client unlike CHAR.
    It is good that you are rude to me , so that I learned a lesson not help others much.
    If you think the above explanation is also wrong , there are other experts in this forum , they will comment and not you alone

  • Pass a date parameter to Stored Procedure

    Hello friends,
    Can you help to pass a date parameter to Stored procedure from JSP. This is my code:
    In Oracle 9i I have this:
    PROCEDURE SP_EDORES(
    pfechaini IN hist_pol_reclama.hrc_fecha_contabilidad%Type, <-- This is a date field
    pfechafin IN hist_pol_reclama.hrc_fecha_contabilidad%Type, <-- This is a date field
    p_recordset OUT PKG_REP_CIERRE.cursor_type) AS
    In JSP have this:
    CallableStatement stmt = (CallableStatement)conn.prepareCall( "begin PKG_REP_CIERRE.SP_EDORES(?,?,?); end;" );
    stmt.registerOutParameter(3,oracle.jdbc.driver.OracleTypes.CURSOR);
    stmt.setDate(1,Date.valueOf("01-06-2005"));
    stmt.setDate(2,Date.valueOf("30-06-2005"));
    ResultSet rset = (ResultSet)stmt.getObject(3);
    while (rset.next()) {
    %>
    <TR>
    <TD ALIGN=CENTER> <%= rset.getString(1) %> </TD>
    <TD ALIGN=CENTER> <%= rset.getString(2) %> </TD>
    <TD ALIGN=CENTER> <%= rset.getString(3) %> </TD>
    <TD ALIGN=CENTER> <%= rset.getInt(4) %> </TD>
    </TR>
    <%
    The Stored Procedure returns de Result set, however I think does not recognized the date format because I need it with this format dd-mm-yyyy.
    Thanks in advance

    to use Date you will need the oracle package.
    u can try this other solution: use String, not Date
    CallableStatement stmt = (CallableStatement)conn.prepareCall( "begin PKG_REP_CIERRE.SP_EDORES(?,?,?); end;" );
    stmt.registerOutParameter(3,oracle.jdbc.driver.OracleTypes.CURSOR);
    stmt.setString(1,"01-06-2005");
    stmt.setString(2,"30-06-2005");
    ResultSet rset = (ResultSet)stmt.getObject(3);
    while (rset.next()) {
    %>
    if this don't work you can change your PL/SQL to get Strings and do the conversion with TO_DATE in the sql statement.

  • Passing parameter into stored procedure

    Hi guys,
    I have a big problem here passing as a parameter in stored
    procedure.
    If i pass as a parameter in where clause it is working fine.
    Whenever i pass the parameter in order by it was not working..
    How to implement this issue????
    Here i am giving the example for package:
    PACKAGE XTRA.TEST_STATUS
    AS
    TYPE GenericCurTyp IS REF CURSOR;
    PROCEDURE SP_MAIN
    ( insortgroup IN VARCHAR2,GENERAL_CUR IN OUT GenericCurTyp);
    END TEST_STATUS;
    PACKAGE BODY XTRA.TEST_STATUS
    AS
    PROCEDURE SP_MAIN
    ( insortgroup IN VARCHAR2, GENERAL_CUR IN OUT GenericCurTyp
    ) AS
    BEGIN
    OPEN GENERAL_CUR FOR
    select last_name,first_name from applicant Order By insortgroup;
    END SP_MAIN;
    END TEST_STATUS;
    Passing as a parameter i am getting the below details.
    LAST_NAME FIRST_NAME
    ASFSDAF DASDFASF
    Ad DASD
    Adams John
    DANA WITEST
    If i hot code the parameter insortgroup to last_name
    i am getting the below values:
    LAST_NAME FIRST_NAME
    'ANNUNZIO GIANCOLA GABRIEL
    0'BRIEN ARMA
    0120453EZ ESTANISLAO
    082479 ELIZABETH
    Thanks,
    Rao

    CREATE OR REPLACE PACKAGE xtra.test_status
    AS
      TYPE GenericCurTyp IS REF CURSOR;
      PROCEDURE sp_main
        (insortgroup IN     VARCHAR2,
         general_cur IN OUT GenericCurTyp);
    END test_status;
    CREATE OR REPLACE PACKAGE BODY xtra.test_status
    AS
      PROCEDURE sp_main
        (insortgroup IN     VARCHAR2,
         general_cur IN OUT GenericCurTyp)
      AS
        select_statement VARCHAR2 (4000) := NULL;
      BEGIN
        select_statement :=
        'SELECT   last_name,
                  first_name
         FROM     applicant
         ORDER BY ' || insortgroup;
        DBMS_OUTPUT.PUT_LINE (select_statement);
        OPEN general_cur FOR select_statement;
      END sp_main;
    END test_status;

Maybe you are looking for