Calling a function from sql*plus

I can call my procedure from sql *plus
by doing
sql>call Proc_name(x,y);
How do you call a function?
null

John,
I think moifying the statement
CREATE OR REPLACE PROCEDURE "OGUSER"."OGX1" (user_county in integer, user_permit in integer )
TO
CREATE OR REPLACE FUNCTION "OGUSER"."OGX1" (user_county in integer, user_permit in integer ) return NUMBER is
AND before end you will have to add a return statement
(Probably
return 0;
exception
when others then
return 1;
end;
This will change your procedure to a function but I am not sure you'll be able to see your dbms_output's, if you call the function using select ...
<BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by john saucer ([email protected]):
I want to turn my procedure into a function.
So I can call it with a select statement.
I'm kind of having problems with the return statement at the top and bottom.
I don't quite understand how to declare the type in the return. My procedure calculates 2 pl/sql tables....
My procedure looks like.
CREATE OR REPLACE PROCEDURE "OGUSER"."OGX1" (user_county in integer, user_permit in integer )
as
i integer :=0;
j integer :=0;
type dept_table_type is table of ogxtest%rowtype
index by binary_integer;
type dept2_table_type is table of ogxtest%rowtype
index by binary_integer;
my_dept_table dept_table_type;
my_dept2_table dept2_table_type;
v_cotemp number := user_county;
v_permittemp number := user_permit;
v_origcotemp number := user_county;
v_origpermittemp number := user_permit;
v_count number(2) :=1;
v_count2 number(2) := 1;
v_oldcount number(2) :=1;
v_oldcount2 number(2) := 1;
begin
select count(*) into v_count from ogxtest where oco=v_cotemp and opermit=v_permittemp;
select count(*) into v_oldcount from ogxtest where nco=v_cotemp and npermit=v_permittemp;
while v_count >= 1 LOOP
i := i+1;
v_count2 := v_count2 +1;
select *
into my_dept_table(i)
from ogxtest where oco=v_cotemp and opermit=v_permittemp;
v_cotemp := my_dept_table(i).nco;
v_permittemp := my_dept_table(i).npermit;
select count(*) into v_count from ogxtest where oco=v_cotemp and opermit=v_permittemp;
end loop;
while v_oldcount >= 1 LOOP
j := j+1;
v_oldcount2 := v_oldcount2 +1;
select *
into my_dept2_table(j)
from ogxtest where nco=v_origcotemp and npermit=v_origpermittemp;
v_origcotemp := my_dept2_table(j).oco;
v_origpermittemp := my_dept2_table(j).opermit;
select count(*) into v_oldcount from ogxtest where nco=v_origcotemp and npermit=v_origpermittemp;
end loop;
for i in 1..v_count2-1
loop
dbms_output.put_line(' reassigned to - orig county ' | |my_dept_table(i).oco | | ' orig permit ' | |my_dept_table(i).opermit| | ' new county ' | |
my_dept_table(i).nco | | ' new permit ' | |my_dept_table(i).npermit );
end loop;
for j in 1..v_oldcount2-1
loop
dbms_output.put_line(' reassigned from - orig county ' | |my_dept2_table(j).oco | | ' orig permit ' | |my_dept2_table(j).opermit| | ' new county ' | |
my_dept2_table(j).nco | | ' new permit ' | |my_dept2_table(j).npermit );
end loop;
end;
<HR></BLOCKQUOTE>
null

Similar Messages

  • Calling a function from SQL prompt that returns a record

    Hi,
    I've been trying to execute a function that is present on a different database. for eg. I am loged on to a database say 'A' and trying to execute a function present in database 'B'. this function is present in a package 'X' which has 2 functions and two procedures. From the packages i am able to execute the two procedures and one of the function.
    So i guess it is not a problem with the access permissions. The function that i am trying to call say function I has got 3 OUT
    parameters and 1 IN parameter. the Function returns a record. When i try to execute this function i get an error. Can you please let me know as to how exactly i need to call this function from the SQL prompt...
    thanx in advance
    null

    Hi Anand,
    As your function has 3 OUT parameters and it returns a record you can not just call it from SQL Plus. You need to write small PL/SQL program and use variables to hold the OUT values and the returned record.
    Good Luck,
    RajKiran
    null

  • How to pass table type variable into function from SQL*PLUS ?

    How to pass a table type variable from sql*plus prompt into a function ?
    Thanx in advance.

    Krishna,
    Do you mean like this?SQL> DECLARE
      2      TYPE t_tbl IS TABLE OF VARCHAR2(20);
      3      l_sample_tbl           t_tbl;
      4
      5      FUNCTION print_contents ( p_tbl IN t_tbl )
      6      RETURN VARCHAR2
      7      IS
      8          l_string            VARCHAR2(1000);
      9      BEGIN
    10          FOR i IN 1..p_tbl.COUNT LOOP
    11              IF (i = 1) THEN
    12                  l_string := p_tbl(i);
    13              ELSE
    14                  l_string := l_string || ', ' || p_tbl(i);
    15              END IF;
    16          END LOOP;
    17          RETURN (l_string);
    18      END print_contents;
    19
    20  BEGIN
    21      l_sample_tbl := t_tbl();
    22      l_sample_tbl.EXTEND;
    23      l_sample_tbl(1) := 'one';
    24      l_sample_tbl.EXTEND;
    25      l_sample_tbl(2) := 'two';
    26      l_sample_tbl.EXTEND;
    27      l_sample_tbl(3) := 'three';
    28      l_sample_tbl.EXTEND;
    29      l_sample_tbl(4) := 'four';
    30      l_sample_tbl.EXTEND;
    31      l_sample_tbl(5) := 'five';
    32      DBMS_OUTPUT.PUT_LINE(print_contents(l_sample_tbl));
    33  END;
    34  /
    one, two, three, four, five
    PL/SQL procedure successfully completed.
    SQL> HTH,
    T.

  • Calling the function from SQL query

    Hi,
    I am trying to run the below statement,
    Select to_number(apps.pay_balance_pkg.get_value( 326, :paa.assignment_action_id,to_date ('31032011','ddmmyyyy'))) from dual;
    getting an error as :
    ORA-14552 cannot perform a DDL, commit or rollback inside a query or DML
    ORA - 06512 at apps.pay_balance_pkg , line 4526.
    How can I execute this funciton "apps.pay_balance_pkg.get_value" from sql query?
    Thanks in advance.

    user1175432 wrote:
    Hi,
    I am trying to run the below statement,
    Select to_number(apps.pay_balance_pkg.get_value( 326, :paa.assignment_action_id,to_date ('31032011','ddmmyyyy'))) from dual;
    getting an error as :
    ORA-14552 cannot perform a DDL, commit or rollback inside a query or DML
    ORA - 06512 at apps.pay_balance_pkg , line 4526.
    How can I execute this funciton "apps.pay_balance_pkg.get_value" from sql query?
    Thanks in advance.If the function is performing DDL, commit or rollback inside it then you will not be able to call it from an SQL statement.
    Either change the function so it doesn't perform DDL, commit or rollback, or use a different means to obtain the information you want (assuming you can't change the function)

  • Call external function from SQL query

    Hi,
    I am new to PL/SQL programming.I don't think this is possible but please let me know if there is a way to achieve this. I have a function written in VB.net and I would want to call from the query.
    create table temp as select id, callvbfunction(note_text) from temp2
    Here callvbfunction is the vb.net function.I need to pass note_text field value to the function.
    Thanks..

    Yes it is possible.
    No idea how to specifically call a .Net function (from Oracle) as I do not do Windows (except for playing games ;-) ). But external procedures (extproc) and Java stored procs can be wrapped by PL/SQL wrapper functions and used in SQL statements.

  • Can call a function from SQL COMMAND but can't from the SHUTTLE help please

    I've read this article
    ARTICLE
    I've written the code in a function called SURVEY_USERS that takes one variable
    when I run the following in the SQL builder:
    SELECT SURVEY_USERS('canns') from DUAL;I get
    SELECT smteam.division_manager DS, smteam.division_manager RV from SMTEAM where smteam.division_manager=canns and rownum = 1
    UNION
    SELECT SMTEAM.dept_manager DS, smteam.dept_manager RV from SMTEAM LEFT where smteam.division_manager=canns
    UNION
    SELECT smteam.wdmanagername DS, smteam.wdmanagername RV from SMTEAM where smteam.division_manager=cannswhich is what I want but when I put in into the "list of values definition".
    RETURN SCREPORTS.SURVEY_USERS('canns');I get
    Error     ORA-06550: line 1, column 188: PL/SQL: ORA-00904: "CANNS": invalid identifier ORA-00904: "CANNS": invalid identifier ORA-06550: line 1, column 7: PL/SQL: SQL Statement ignored ORA-00904: "CANNS": invalid identifierI'm just confused as to what I'm doing wrong. I'm passing the same thing to the function...and it appears to be working in the SQL workshop and not the actual LOV Shuttle.
    Edited by: bostonmacosx on Sep 12, 2012 3:45 PM

    Here is some of the function
    create or replace function "SURVEY_USERS"
    (app_user in VARCHAR2)
    return VARCHAR2
    is
      vp_exists INTEGER;
      ed_exists INTEGER;
      dr_exists INTEGER;
      mngr_exists INTEGER;
    begin
    SELECT COUNT(*) into vp_exists
      FROM smteam
      WHERE area_manager= app_user
      AND ROWNUM = 1;
      SELECT COUNT(*) INTO ed_exists
      FROM smteam
      WHERE division_manager = app_user
      AND ROWNUM = 1;
      SELECT COUNT(*) INTO dr_exists
      FROM smteam
      WHERE dept_manager = app_user
      AND ROWNUM = 1;
      SELECT COUNT(*) INTO mngr_exists
      FROM smteam
      WHERE wdmanagername = app_user
      AND ROWNUM = 1;
    --dbms_output.put_line (vp_exists);
    --dbms_output.put_line (ed_exists);
    --dbms_output.put_line (dr_exists);
    --dbms_output.put_line (mngr_exists);
    IF (vp_exists = 1) THEN
      RETURN 'SELECT smteam.area_manager DS,smteam.area_manager RV from SMTEAM where smteam.area_manager='''||app_user||''' and ROWNUM = 1
       UNION
       SELECT smteam.division_manager DS, smteam.division_manager RV from SMTEAM where smteam.area_manager='''||app_user||'''
       UNION
         SELECT smteam.dept_manager DS, smteam.dept_manager RV from SMTEAM  where smteam.area_manager='''||app_user||'''
       UNION
        SELECT smteam.wdmanagername DS, smteam.wdmanagername RV from SMTEAM  where smteam.area_manager='''||app_user||'''';
    END IF;
    IF (ed_exists = 1 and vp_exists=0) THEN
        RETURN 'SELECT smteam.division_manager DS, smteam.division_manager RV from SMTEAM  where smteam.division_manager='''||app_user||''' and rownum = 1
       UNION
         SELECT SMTEAM.dept_manager DS, smteam.dept_manager RV from SMTEAM LEFT where smteam.division_manager='''||app_user||'''
       UNION
        SELECT smteam.wdmanagername DS, smteam.wdmanagername RV from SMTEAM where smteam.division_manager='''||app_user||'''';
      END IF;
    IF (dr_exists = 1 and ed_exists=0 and vp_exists=0) THEN
         RETURN 'SELECT smteam.dept_manager DS, smteam.dept_manager RV from SMTEAM  where smteam.dept_manager=:'''||app_user||'''and rownum = 1
       UNION
        SELECT smteam.wdmanagername DS, smteam.wdmanagername RV from SMTEAM  where smteam.dept_manager='''||app_user||'''';
      END IF;
    IF (mngr_exists = 1 and ed_exists=0 and vp_exists=0 and dr_exists=0) THEN
        RETURN  'SELECT smteam.wdmanagername DS, smteam.wdmanagername RV from SMTEAM  where smteam.wdmanagername=:'''||app_user||''' and rownum = 1';
      END IF;
    END;
    Edited by: bostonmacosx on Sep 12, 2012 3:56 PM

  • Calling a function from SQL that has Out Parameters

    Hello folks,
    I am not sure if this is do-able, but here is my scenrio at hand. I have a database function that accepts a few IN parameters and OUT parameters. I want one of the Out parameters to display as part of my select statement. Is this possible?
    Thanks

    No you cannot use a function with out parameters in sql statements.
    If possible make the function return that value, then use it in select.( imean instead of OUT parameter, get that OUT parameter through RETURN)
    G.

  • How to call javascript function from PL/SQL procedure

    Can anybody advice me how to call javascript function from PL/SQL procedure in APEX?

    Hi,
    I have a requirement to call Javascript function inside a After Submit Process.
    clear requirement below:
    1. User selects set of check boxes [ say user want to save 10 files and ticks 10 checkboxes]
    2. user clicks on "save files" button
    3. Inside a After submit process, in a loop, i want to call a javascript function for each of the file user want to save with the filename as a parameter.
    Hope this clarify U.
    Krishna.

  • Calling stored proc (with 2 IN and 3 OUT) - from SQL Plus

    This is the signature of my stored proc:
    CREATE OR REPLACE PROCEDURE myschema.myproc
       p_usr_name     IN  VARCHAR2,    
       p_send_tmstmp  IN  DATE,    
       p_ret_value    OUT NUMBER,
       p_err_code     OUT VARCHAR2
    )If I need to call it from sql plus, how do I need to pass the arg?
    This is what I am doing
    execute myschema.myproc('abc123','02-MAY-2008');
    What is wrong here? If someone could help. Thx!

    Try something like this
    var usr_name    varchar2(30)  
    var send_tmstmp varchar2(11)  
    var ret_value   number
    var err_code    varchar2(10)
    begin
    :usr_name    := 'abc123';
    :usr_name := '02-MAY-2008';
    myschema.myproc ( p_usr_name           => :usr_name,
                      p_send_tmstmp        => TO_DATE( :usr_name, 'DD-MON-YYYY' ),
                      p_ret_value          => :ret_value,
                      p_err_code           => :err_code);
    end;
    print ret_value;
    print err_code;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Calling a BOOLEAN returning function from SQL

    Hello All,
    I have created below function which return BOOLEAN value :
    CREATE OR REPLACE FUNCTION FUNC_1
    P_EMPID IN emp.empno%type
    )RETURN BOOLEAN
    AS
    L_VAR NUMBER;
    BEGIN
    SELECT 1 INTO L_VAR
    FROM EMP
    WHERE EMPNO = P_EMPID;
    IF L_VAR = 1 THEN
    RETURN TRUE;
    ELSE
    RETURN FALSE;
    END IF;
    END;Now I want to call this function from SELECT but I know that SQL does not support BOOLEAN value so I tried in other way i.e. via CASE
    SELECT CASE FUNC_1(7788)
           WHEN TRUE THEN 'TRUE'
           WHEN FALSE THEN 'FALSE'
           ELSE 'NULL'
           END CASE
    FROM DUALBut it is giving me error "ORA-00904: "FALSE": invalid identifier'
    How can I achieve this ?
    Thanks & Regards,
    Rakesh

    Hi Rakesh,
    Why cant you try something like this, When BOOLEAN type is not supported in SQL.
    Here I have made the return value a number. And, at case comparison, we get the BOOLEAN
    result as TRUE of FALSE.
    CREATE OR REPLACE FUNCTION func_1 (p_empid IN emp.empno%TYPE)
       RETURN NUMBER
    AS
       l_var   NUMBER;
    BEGIN
       SELECT count(*)
         INTO l_var
         FROM emp
        WHERE empno = p_empid;
       IF l_var = 1
       THEN
          RETURN 1;
       ELSE
          RETURN 0;
       END IF;
    END;And,
    SELECT CASE func_1 (55656)
              WHEN 1
                 THEN 'TRUE'
              WHEN 0
                 THEN 'FALSE'
           END
      FROM DUAL;Which return TRUE if the Employee Number Exists and FALSE if doesnot.
    Thanks,
    Shankar.

  • Execute a mapping deployed with OWB 9.0.4 from SQL*Plus

    Hello,
    I could execute a mapping designed with OWB 9.0.3 from SQL*Plus with the next sentence:
    SQL> exec my_mapping.main;
    But now, with OWB 9.0.4, mappings are deployed as functions (in 9.0.3 were deployed as procedures) and they need parameters.
    Somebody know how I can execute deployed mappings with OWB 9.0.4 from SQL*Plus? I don't know the parameters I need to call a mapping.
    Thanks in advance,
    Pedro.

    Well, I've solved the problem with roles but
    I've executed the script called sqlplus_exec_template.sql and it fails at Stage 2 because the next sentence
    l_audit_execution_id := wb_rt_api_exec.open(l_task_type, l_task_name, l_location_name);
    returns me NULL.
    It is not clear the value that the variable called l_location_name have to stored. The script explain that this variable store the physical name of the
    location to which the task was deployed. I understand that this variable have to store the schema where the mapping was deployed. That's right?
    So I called the script in this manner:
    SQL> @sqlplus_exec_template OWBRUN904I OJBHT PLSQL MY_MAPPING "," "," ;
    where OWBRUN904I is the name of the Runtime Repository Schema, OJBHT is the
    schema where MY_MAPPING is deployed, PLSQL is the task type and MY_MAPPING is
    the name of the mapping I've designed.
    Can you tell me why the scripts fails?
    Regards,
    Pedro

  • Oracle:JDBC Call returns no results, SQL*Plus returns 1 record, Please help

    Any help would be greatly appreciated.
    Running 9.2.0.5.0, and using latest 9.2 JDBC 1.4_g drivers in thin mode.
    Execute the following query from SQL*Plus and it returns one row, from JDBC using a PreparedStatement, I get no results. Here's the query, table def, record, etc.:
    Query:
    SELECT
    ID_WEB_FRM,ID_WEB_SIT,CDE_LVL_1_FUNC,
    CDE_LVL_2_FUNC,NUM_WEB_FUNC_PG,NUM_WEB_PG_ID
    FROM
    WEB_FRM
    WHERE
    ID_WEB_FRM = ' '
    OR
    (ID_WEB_SIT = 'test' AND CDE_LVL_1_FUNC = ' '
    AND CDE_LVL_2_FUNC = 'u2T' AND NUM_WEB_FUNC_PG = 1
    AND NUM_WEB_PG_ID = 0)
    Record returned from SQL*Plus:
    ID_WEB_FRM ID_WEB_SIT CDE CDE NUM_WEB_FUNC_PG NUM_WEB_PG_ID
    NfRRmc5XZu test u2T 1 0
    Both in the data returned and the query, there are no blanks, but they are a single space instead (hard to see in message here).
    Java code:
    int count = 1;
    findDBNameStatement.setString(count++," ");
    findDBNameStatement.setString(count++,form.getSiteID());
    findDBNameStatement.setString(count++," ");
    findDBNameStatement.setString(count++, form.getFunctionID());
    findDBNameStatement.setInt(count++,form.getPageNumber());
    findDBNameStatement.setInt(count++,form.getSectionNumber());
    ResultSet resultSet = findDBNameStatement.executeQuery();
    ResultSetMetaData metaData = resultSet.getMetaData();
    resultSet.next() returns false
    DB table:
    CREATE TABLE web_frm (
    ID_WEB_FRM varchar2(10) NOT NULL,
    ID_WEB_SIT varchar2(20) NOT NULL,
    NAM_WEB_FRM varchar2(40),
    TXT_EMAIL_SUBJ varchar2(50),
    CDE_LVL_1_FUNC char(3),
    CDE_LVL_2_FUNC char(3) NOT NULL,
    NUM_WEB_FUNC_PG int NOT NULL,
    NUM_WEB_PG_ID smallint NOT NULL,
    DTE_WEB_FRM_EFF date NOT NULL,
    DTE_WEB_FRM_TRM date,
    CDE_VLDT_RUL char(3),
    DTE_LAST_EXPRT date,
    TXT_CNFRMN_MSG varchar2(4000),
    IND_UPDT_ALWD char(1) NOT NULL,
    TXT_RECAP_HDR varchar2(4000),
    TXT_RECAP_FTR varchar2(4000),
    CDE_WEB_OBJ char(3),
    NUM_MAX_FRM_WIDTH number(4,0),
    IND_RECAP_PG char(1) NOT NULL,
    IND_CNFRM_PG char(1) NOT NULL,
    IND_DSPL_CNFRM_NUM char(1) NOT NULL,
    CNT_SUBM_MAX int,
    TXT_CHCE_ADD_MSG varchar2(255),
    TXT_CHCE_MOD_MSG varchar2(255),
    TXT_WEB_HDR varchar2(4000),
    TXT_WEB_FTR varchar2(4000),
    TXT_WAIT_LIST_MSG varchar2(255),
    FORMOBJECTHEIGHT int NOT NULL,
    FORMOBJECTWIDTH int NOT NULL
    ALTER TABLE web_frm ADD ( CONSTRAINT PK_web_frm PRIMARY KEY (ID_WEB_FRM));
    ALTER TABLE web_frm ADD ( CONSTRAINT UK_web_frm UNIQUE (ID_WEB_SIT,CDE_LVL_1_FUNC,CDE_LVL_2_FUNC,NUM_WEB_FUNC_PG,NUM_WEB_PG_ID)) ;
    Thanks,
    Matt

    That's not quite right. From the javadocs:
    next
    public boolean next()
    throws SQLException
    Moves the cursor down one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
    If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.
    Returns:
    true if the new current row is valid; false if there are no more rows
    Throws:
    SQLException - if a database access error occurs

  • Calling user function from Interface mapping

    I am getting error "Bad query:ORA-00904: invalid identifier" while calling function in the mapping of an interface.
    Can some one provide the syntax of calling user function from interface mapping.
    Thanks,
    RP

    user452108 wrote:
    Can some one provide the syntax of calling user function from interface mapping.Oracle's Call Iinterface, the OCI, does not work differently when coding using a Dvorak keyboard, or writing code using a pretty pink font in the editor.. or coding the call from an interface mapping (whatever the hell that that is).
    You have 2 types of calls. SQL and PL/SQL.
    To call a function via SQL, it can be done using a the standard cursor interface. E.g.
    select MyFunkyFunction from dualIt will return the function value via a single row with a single column. The standard cursor fetch and close cursor calls are used.
    To call it via PL/SQL, an anonymous PL/SQL block is needed, and the caller needs to use a bind variable to receive the value from the function. The anon block will look as follows:
    begin
      :bindVar := MyFunkyFunction;
    end;Refer to your client's abstract layer for interfacing with the Oracle Call Interface, on how to deal with bind variables.

  • How to call oracle function from ejb3

    i'm trying to call an oracle query-function from ejb3.
    The oracle function:
    create or replace FUNCTION getSecThreadCount(secId in NUMBER,avai in NUMBER)
    RETURN SYS_REFCURSOR is cur SYS_REFCURSOR;
    m_sql VARCHAR2(250);
    BEGIN
    m_sql:='select count(thrId) from thread where secId='|| secid||'
    and thrAvai='|| avai;
    open cur for m_sql;
    return cur;
    END;
    I'v tried several ways to call it,but all failed:
    1. the calling code:
    public Object getSectionThreadCount(int secId,int avai){
              Query query=manager.createNativeQuery("{call getSecThreadCount(?,?) }");     
              query.setParameter(1, secId);
              query.setParameter(2, avai);
              return query.getSingleResult();
    but i got the exception:
    Exception in thread "main" javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query; nested exception is: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    Caused by: java.sql.SQLException: ORA-06550: row 1, col 7:
    PLS-00221: 'GETSECTHREADCOUNT' not procedure or not defined
    ORA-06550: row 1, col 7:
    PL/SQL: Statement ignored
    2. the calling code:
    @SqlResultSetMapping(name = "getSecThreadCount_Mapping")
    @NamedNativeQuery(name = "getSecThreadCount",
    query = "{?=call getSecThreadCount(:secId,:avai)}",
    resultSetMapping = "getSecThreadCount_Mapping",
    hints = {@QueryHint(name = "org.hibernate.callable", value = "true"),
              @QueryHint(name = "org.hibernate.readOnly", value = "true")})
    public Object getSectionThreadCount(int secId,int avai){
              Query query=manager.createNamedQuery("getSecThreadCount");     
              query.setParameter("secId", secId);
              query.setParameter("avai", avai);
              return query.getSingleResult();
    but i run into the exception:
    Exception in thread "main" javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query; nested exception is: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    Caused by: java.sql.SQLException: lost in index IN or OUT parameter:: 3
    By the way, i have successfully called the function from hibernate. And i use oracle 11g, JBoss5 RC1.
    Could anyone tell me how to call the function from EJB3?
    Thanks.

    Here's a working model:
    package.procedure: (created in example schema scott)
    CREATE OR REPLACE package  body data_pkg as
      type c_refcursor is ref cursor;
      -- function that return all emps of a certain dept
      function getEmployees ( p_deptId in number
      return c_refcursor
      is
        l_refcursor c_refcursor;
      begin
         open l_refcursor
        for
              select e.empno as emp_id
              ,        e.ename as emp_name
              ,        e.job   as emp_job
              ,        e.hiredate as emp_hiredate
              from   emp e
              where  e.DEPTNO = p_deptId;
        return l_refcursor;
      end getEmployees;
    end data_pkg;
    /entity class:
    package net.app.entity;
    import java.io.Serializable;
    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedNativeQuery;
    import javax.persistence.QueryHint;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    @SuppressWarnings("serial")
    @Entity
    @Table (name="emp")
    @SequenceGenerator(name = "EmployeeSequence", sequenceName = "emp_seq")
    @NamedNativeQuery( name = "getEmpsByDeptId"
                   , query = "{ ? = call data_pkg.getEmployees(?)}"
                   , resultClass = Employee.class
                   , hints = { @QueryHint(name = "org.hibernate.callable", value = "true")
                          , @QueryHint(name = "org.hibernate.readOnly", value = "true")
    public class Employee implements Serializable
        @Id
        @Column(name="emp_id")
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EmployeeSequence")
        private int id;
        @Column(name="emp_name")
        private String name;
        @Column(name="emp_job")
        private String job;
        @Column(name="emp_hiredate")
        private Date hiredate;
        // constructor
        public Employee (){}
        // getters and setters
        public int getId()
         return id;
    etc...session bean:
    package net.app.entity;
    import java.util.ArrayList;
    import java.util.List;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    import net.app.entity.Employee;
    import net.app.iface.ScottAdmin;
    @Stateless
    public class ScottAdminImpl implements ScottAdmin
        @PersistenceContext
        private EntityManager entityManager;
        @SuppressWarnings("unchecked")
        public List<Employee> getEmployeesByDeptId(int deptId)
         ArrayList<Employee> empList;
         try
             Query query = entityManager.createNamedQuery("getEmpsByDeptId");
             query.setParameter(1, deptId);
             empList = (ArrayList<Employee>) query.getResultList();
             return empList;
         catch (Exception e)
             e.printStackTrace(System.out);
             return null;
    }client:
    package net.app.client;
    import java.util.List;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import net.app.entity.Employee;
    import net.app.iface.ScottAdmin;
    public class ScottClient
        public static void main(String[] args)
         try
             // create local interface
             InitialContext ctx = new InitialContext();
             ScottAdmin adminInterface = (ScottAdmin) ctx.lookup("ScottAdminImpl/remote");
             // select employees by deptno
             int deptno = 20;
             List<Employee> empList = adminInterface.getEmployeesByDeptId(deptno);
             // output
             System.out.println("Listing employees:");
             for (Employee emp : empList)
              System.out.println(emp.getId() + ": " + emp.getName() + ", " + emp.getJob() + ", " + emp.getHiredate());
         catch (NamingException e)
             e.printStackTrace(System.out);
    }Basically you just ignore the refcursor outbound parameter.
    This is a stored function, have yet to try outbound refcursor parameters in stored procedures...
    Edited by: _Locutus on Apr 2, 2009 2:37 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Calling a function from ananymous block

    All,
    I have created a function which is to create a table with the given string. Below is the code.
    CREATE OR REPLACE
    FUNCTION tcr(
    name IN VARCHAR2)
    RETURN VARCHAR2
    IS
    vsql VARCHAR2(100);
    vmsg VARCHAR2(100);
    BEGIN
    vsql :='create table '||name||' ( a number(4) )';
    EXECUTE immediate vsql;
    dbms_output.put_line('craeted');
    vmsg:='creation msg';
    RETURN vmsg;
    EXCEPTION
    WHEN OTHERS THEN
    RETURN sqlerrm;
    END;
    When I am calling this from a SELECT stmt giving me the below error
    SELECT tcr('test1') FROM dual; ORA-14552: cannot perform a DDL, commit or rollback inside a query or DML
    And when I called this from an anonymous block giving me the error again.
    DECLARE
    vmsg VARCHAR2(200);
    BEGIN
    vmsg:= tcr('test11');
    dbms_output.put_line(vmsg);
    END;
    ORA-01031: insufficient privilegesCan we use a DDL inside a function and can be called from a SELECT Query. If not what happening inside it when we call from a query, am not able to understand. Expecting a clear explanation.
    Thanks
    Edited by: 968217 on Apr 17, 2013 11:08 AM

    >
    Can we use a DDL inside a function and can be called from a SELECT Query. If not what happening inside it when we call from a query, am not able to understand.
    >
    No - you can NOT use DDL inside a function used in a SELECT query.
    See 'Invoking Stored PL/SQL Functions from SQL Statements' in the Advanced Application Developer's Guide
    http://docs.oracle.com/cd/B28359_01/appdev.111/b28424/adfns_packages.htm#ADFNS00908
    The section 'Controlling Side Effects' has the information about restrictions
    >
    Restrictions
    When a SQL statement is run, checks are made to see if it is logically embedded within the execution of an already running SQL statement. This occurs if the statement is run from a trigger or from a subprogram that was in turn invoked from the already running SQL statement. In these cases, further checks occur to determine if the new SQL statement is safe in the specific context.
    The following restrictions are enforced on subprograms:
    A subprogram invoked from a query or DML statement might not end the current transaction, create or rollback to a savepoint, or ALTER the system or session.
    A subprogram invoked from a query (SELECT) statement or from a parallelized DML statement might not execute a DML statement or otherwise modify the database.
    A subprogram invoked from a DML statement might not read or modify the particular table being modified by that DML statement.
    >
    Since DDL issues a COMMIT it would 'end the current transaction' which, as the first item above says, is not allowed.
    Yes - using the AUTONOMOUS_TRANSACTION pragma can side-step that issue but that would be a serious misuse of the functionality.

Maybe you are looking for