Calling Oracle function in JDBC
Hi,
The function in Oracle is defined as
FUNCTION SETUP RETURNS BOOLEAN
Argument Name Type In/Out Default?
PI_NE_ID NUMBER IN
PI_PI_AID VARCHAR2 IN
PI_ATTR_NAME_LIST_ID VARCHAR2 IN
PI_NETYPE VARCHAR2 IN DEFAULT
PI_CLLI VARCHAR2 IN DEFAULT
DI_CATEGORY VARCHAR2 IN/OUT
MSG VARCHAR2 IN/OUT
My code in Java is
CallableStatement stmt = con.prepareCall("{? = call ges.
Setup(?,?,?,?,?,?,?)}");
System.out.println( " formed call statement" );
stmt.setInt( 1, 6);
stmt.setString( 2, "COM-5004" );
stmt.setString( 3, "TS35-COM" );
stmt.setString( 4, "*" );
stmt.setString( 5, "*" );
stmt.setString( 6, "C" );
stmt.setString( 7, msg );
stmt.registerOutParameter( 8, Types.BIT );
stmt.registerOutParameter( 6, Types.VARCHAR );
stmt.registerOutParameter( 7, Types.VARCHAR );
stmt.execute();
I have tried commenting registerOutParameter for 6 and 7. But I get the error
Connectingjava.sql.SQLException: ORA-06550: line 1, column 13:
PLS-00382: expression is of wrong type
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Can anybody please tell what is the problem.
I am using JDK1.3.
When I give Type.BOOLEAN instead of BIT I get compilation error.
Thanks
Smitha
Hi Smintha,
Oracle does not support the return of Boolean over JDBC. To work around this problem you have to write a wrapper function around your original function which returns then for example a number value that indicates true or false.
I assume that the reason for not returning boolean values is that Oracle's boolean value is threefold it can either be true, false or null where null is neither success or failure but rather non-existing.
Let me know if you need any further examples about this.
Hope this helps,
Kalle
Similar Messages
-
Call Oracle Function via JDBC Adapter
Hi to everybody,
using JDBC connection with an Oracle DB, from XI I manage to send messages to execute SQL statements or Stored Procedures. Does anybody know if there is a way to call also an Oracle Function?
Thanks a lot for any help...
IlariaHi Illaria,
I think i agree with Michal. The solution to your problem would be to go for a stored procedure. The link on SDN help only tells us that a stored procedure can be executed and does not discuss about oracle functions.
http://help.sap.com/saphelp_nw04/helpdata/en/2e/96fd3f2d14e869e10000000a155106/content.htm
So, Stored Procedures, it has to be.
Regards,
Bhavesh -
Oracle Function in JDBC Adapter
Dear All
Can we execute an oracle fucntion using receiver jdbc adapter? if yes then what should be the structure
I have gone through following links but the soluiotn is not clear
Using PI - Calling a Function in Oracle
Regards
SourabhI think two possible ways. You might want to write stored procedure and inside your stored procedure call oracle function. The second option is as below. In access tag write your query with standard functions. placeholder is to pass values for the variable.
<StatementName>
<anyName action=u201D SQL_QUERYu201D | u201CSQL_DMLu201D>
<access>SQL-String with optional placeholder(s)</access>
<key>
<placeholder1>value1</placeholder1>
<placeholder2>value2<placeholder2>
</key>
</anyName >
</StatementName>
Ex:
SELECT '03.12.2004:10:34:24' "Now",
TO_CHAR(hiredate,'DD.MM.YYYY:HH24:MI:SS') "Hiredate",
TO_DATE('03.12.2004:10:34:24','DD.MM.YYYY:HH24:MI:SS')
- hiredate "Hired since [Days]"
FROM emp;
where to_char is the oracle function. -
JAVA Calling Oracle Function and Returning OBJECT
HI,
I am working as a developer in java/j2ee project.
I am facing one issue:
I need to call Oracle function from java code. Oracle User define function is residing in oracle package and returning Object which contains data.
Can you please help me
With Best Regardsgolduniya wrote:
I need to call Oracle function from java code. Oracle User define function is residing in oracle package and returning Object which contains data.
Can you please help meIt requires a great deal of Oracle jdbc driver specific code.
[http://download-west.oracle.com/docs/cd/B10501_01/java.920/a96654/oraint.htm#1012664] -
Ora-06502 while calling oracle function
I am using 9.2.0.4.0 database.
I have vb.net application that uses oracle provider for .net to connect to database.
I am calling Oracle function which returns varchar2 value back.
when i execute cmd2.ExecuteNonQuery, I get ora-06502 error.
CREATE OR REPLACE FUNCTION ZZZ_TEMP( p_val IN VARCHAR2) RETURN varchar2
AS
BEGIN
RETURN 'HELLO';
EXCEPTION WHEN OTHERS THEN
RETURN SQLCODE||' - '||SUBSTR(SQLERRM,1,100);
END;
************** vb.net code
Dim cmd2 As New Oracle.DataAccess.Client.OracleCommand(UserSchemaName & ".ZZZ_TEMP", con)
Dim VAL As String
Try
cmd2.Parameters.Add("RetVal", Oracle.DataAccess.Client.OracleDbType.Varchar2, ParameterDirection.ReturnValue)
cmd2.Parameters.Add("p_val", Oracle.DataAccess.Client.OracleDbType.Varchar2, ParameterDirection.Input).Value = "XYZ"
cmd2.Connection = con
cmd2.CommandType = CommandType.StoredProcedure
cmd2.ExecuteNonQuery()
VAL = cmd2.Parameters("RetVal").Value
Catch ex As Oracle.DataAccess.Client.OracleException
MsgBox(ex.Message)
End TryIf I change this function to retrun number rather than Varchar2 and change my
RetVal parameter as follow it works. I am noticing that there might be a bug when function returns varchar2
cmd2.Parameters.Add("RetVal", Oracle.DataAccess.Client.OracleDbType.int32, ParameterDirection.ReturnValue)
cmd2.Parameters.Add("p_Val", Oracle.DataAccess.Client.OracleDbType.int32, ParameterDirection.Input).valu ="XYZ" -
Calling oracle function in OMB script
Hi
Can anyone please tell me how can i get the returned value of an oracle function in OMB script. or how can i get the value into OMB variable and use it.
Basically i want to set the properties of OWB mapping via OMB script.
Following OMB code sets the max error limit of a mapping.
OMBALTER MAPPING 'MAP_DATA' SET PROPERTIES (MAXIMUM_NUMBER_OF_ERRORS) VALUES ('100')
i dont want to hard code the value 100 rather i want this value to be returned from a function.
If it is not possible then plz tell me how can i set MAXIMUM_NUMBER_OF_ERRORS property of OWB mapping via sql or pl/sql.
Any type of clue will be highly appreciated.
Best RegardsHere is my bare-bones OMB SQL Library to allow you to do pure SQL calls from within OMB+. All I have ever used it for is to run queries, so I don't have a library procedure for calling a function, however if your function is SQL-callable (e.g. select my_func() from dual) then it would work. Either that or you'll want to augment this library to build a procedure that will call and return the results from a java preparedStatement. It's something I've been meaning to do, but haven't got around to it yet.
All you should need to do is save this as it's own tcl file and then source it at the top of your own script, or embed it into your script.
EDIT: Here is a page with some sample code on using java.sql.CallableStatement to call a Pl/SQL procedure from Java which should certainly do the trick for you in conjunction with the basic session control in my library.
http://www.exampledepot.com/egs/java.sql/CallProcedure.html
Cheers,
Mike
package require java
#file omb_sql_library.tcl
proc oracleConnect { serverName databaseName portNumber username password } {
# import required classes
java::import java.sql.Connection
java::import java.sql.DriverManager
java::import java.sql.ResultSet
java::import java.sql.SQLWarning
java::import java.sql.Statement
java::import java.sql.CallableStatement
java::import java.sql.ResultSetMetaData
java::import java.sql.DatabaseMetaData
java::import java.sql.Types
java::import oracle.jdbc.OracleDatabaseMetaData
# load database driver .
java::call Class forName oracle.jdbc.OracleDriver
# set the connection url.
append url jdbc:oracle:thin
append url :
append url $username
append url /
append url $password
append url "@"
append url $serverName
append url :
append url $portNumber
append url :
append url $databaseName
set oraConnection [ java::call DriverManager getConnection $url ]
set oraDatabaseMetaData [ $oraConnection getMetaData ]
set oraDatabaseVersion [ $oraDatabaseMetaData getDatabaseProductVersion ]
puts "Connected to: $url"
puts "$oraDatabaseVersion"
return $oraConnection
proc oracleDisconnect { oraConnect } {
$oraConnect close
proc oraJDBCType { oraType } {
#translation of JDBC types as defined in XOPEN interface
set rv "NUMBER"
switch $oraType {
"0" {set rv "NULL"}
"1" {set rv "CHAR"}
"2" {set rv "NUMBER"}
"3" {set rv "DECIMAL"}
"4" {set rv "INTEGER"}
"5" {set rv "SMALLINT"}
"6" {set rv "FLOAT"}
"7" {set rv "REAL"}
"8" {set rv "DOUBLE"}
"12" {set rv "VARCHAR"}
"16" {set rv "BOOLEAN"}
"91" {set rv "DATE"}
"92" {set rv "TIME"}
"93" {set rv "TIMESTAMP"}
default {set rv "OBJECT"}
return $rv
proc oracleQuery { oraConnect oraQuery } {
set oraStatement [ $oraConnect createStatement ]
set oraResults [ $oraStatement executeQuery $oraQuery ]
# The following metadata dump is not required, but will be a helpfull sort of thing
# if ever want to really build an abstraction layer
set oraResultsMetaData [ $oraResults getMetaData ]
set columnCount [ $oraResultsMetaData getColumnCount ]
set i 1
#puts "ResultSet Metadata:"
while { $i <= $columnCount} {
set fname [ $oraResultsMetaData getColumnName $i]
set ftype [oraJDBCType [ $oraResultsMetaData getColumnType $i]]
#puts "Output Field $i Name: $fname Type: $ftype"
incr i
# end of metadata dump
return $oraResults
# SAMPLE CODE to run a quick query and dump the results. #
#set oraConn [ oracleConnect myserver orcl 1555 scott tiger ]
#set oraRs [ oracleQuery $oraConn "select name, count(*) numlines from user_source group by name" ]
#for each row in the result set
#while {[$oraRs next]} {
#grab the field values
# set procName [$oraRs getString name]
# set procCount [$oraRs getInt numlines]
# puts "Program unit $procName comprises $procCount lines"
#$oraRs close
#oracleDisconnect $oraConnEdited by: zeppo on Nov 25, 2008 7:19 AM -
Can we call a Oracle function using PI? If yes then what should be the structure i.e. shoule that be built like a select ? or SQL_DML or ? Stored Procudure ?
Sample structure with example will helpSure, is possible. You can use an JDBC Adapter (receiver or sender type).
Take a look here:
JDBC ADAPTER
http://help.sap.com/saphelp_nw04/helpdata/en/22/b4d13b633f7748b4d34f3191529946/content.htm
JDBC RECEIVER
http://help.sap.com/saphelp_nw04/helpdata/en/64/ce4e886334ec4ea7c2712e11cc567c/content.htm
JDBC MESSAGE FORMAT
http://help.sap.com/saphelp_nw04/helpdata/en/2e/96fd3f2d14e869e10000000a155106/content.htm
The option to use is an your chose, in according to your requirement.
Usually, I use a StoredProcedure, except for very simple requirements. -
Invoking oracle function thru JDBC Receiver.
Hi Crew,
I have a scenario in which JDBC receiver have to call a Oracle function. Can somebody help me deriving out JDBC sender Data type definition format?
Thanks in Advance
Karthik Kaveriselvan.Hi
/people/siva.maranani/blog/2005/09/16/xi-how-to-on-jdbc-receiver-response
/people/jegathees.waran/blog/2007/03/02/oracle-table-functions-and-jdbc-sender-adapter
/people/bhavesh.kantilal/blog/2006/07/03/jdbc-receiver-adapter--synchronous-select-150-step-by-step
http://help.sap.com/saphelp_nw04/helpdata/en/64/ce4e886334ec4ea7c2712e11cc567c/frameset.htm
Thanks -
I am new to ODI. I need to call a function created on the database which return a value. In ODI I created a variable. In the select (of the variable) I don't know how to call the source table value that needs to be passed to the function.
My oracle function:
create or replace function return_timeid(trans_date in date)
return number is
Result number;
v_trans_date varchar2(30) := to_char(trans_date, 'dd-mon-rrrr hh24miss');
v_hour number := 0;
v_min number := 0;
begin
v_hour := substr(v_trans_date, 13, 2);
v_min := substr(v_trans_date, 15, 2);
case
when v_min between 1 and 30 then
result := (v_hour * 100) + 30;
when v_min = 0 then
result := v_hour * 100;
when v_min > 30 then
result := (v_hour + 1) * 100;
end case;
-- convert 2400 to 0000
if result = 2400 then
result := 0;
elsif result = 2430 then
result := 30;
end if;
return result;
end return_timeid;
The result will be a time ID, depending on the source record value in the source table. How do I keep the time ID in the variable that I created.
This is the select in my variable (Time_ID):
SELECT BIUSER.return_timeid(GPRS_HOME_CDRS.CALL_DATE_DT) FROM dual
this is my error:
904 : 42000 : java.sql.SQLException: ORA-00904: "GPRS_HOME_CDRS"."CALL_DATE_DT": invalid identifier
RegardsI tried to call the function in the mapping. My code:
biuser.return_timeid(GPRS_HOME_CDRS.CALL_DATE_DT)
but then I get the ORA-00936 (missing expression)
My code generated in the operator when loading the flow table:
insert /*+ APPEND */ into BIUSER.I$_FACT_ABIL_GPRS_T
DIMDATASOURCEID,
DIMDATARECORDTYPEID,
DIMDATEID,
DIMTIMEID,
DIMAPNID_IC,
DIMIMSIID,
DIMCALLLOCATIONID,
DIMCAUSERECCLOSEID,
CALLDURATION,
UPLINK_DATAVOLUME,
DOWNLINK_DATAVOLUME,
CALL_CHARGE,
DIMRATEPLANID,
TRANS_DATE,
DIMPEAKID,
DIMTARIFFCODEID,
DIMCHARGEID,
MOBL_NUM,
ACC_LINK_CODE,
CHARGED_UNITS,
CHARGED_DURATION,
CHARGED_VOLUME,
DISCOUNTED_VALUE,
DISCOUNTED_AMOUNT,
FACT_PROCESS_DATE,
CHRONO_NUM,
ORIGINATE_CELL_ID,
STAGE_PROCESS_DATE,
IND_UPDATE
select
case
When length(rtrim(C19_QOS_USED_1_V)) = 7 then 1
else 2
end case,
DIM_DATA_RECORD_TYPE.DIMDATARECORDTYPEID,
DIM_DATE.DIMDATEID,
biuser.return_timeid(C12_CALL_DATE_DT), DIM_APN.DIMAPNID,
to_number(DIM_IMSI_MSISDN.DIMIMSIMSISDNID),
to_number(DIM_CALL_LOCATION.DIMCALLLOCATIONID),
to_number(DIM_TERM_CAUSE.DIMTERMCAUSEID),
C5_CALL_DURATION_N,
.DATA_VOLUME_OUTGOING_1_N,
C17_DATA_VOLUME_INCOMING_1_N,
C1_CALL_CHARGE,
DIM_RATEPLAN.DIMRATEPLANID,
C12_CALL_DATE_DT,
to_number(DIM_RATEPLAN.DIMRATEPLANID),
DIM_TARIFF.DIMTARIFFID,
to_number(DIM_CALLCHARGE_TYPE_TB.DIMCALLCHARGETYPEID),
C2_MOBL_NUM,
C21_ACCOUNT_LINK_CODE_N,
C10_CHARGED_UNITS_N,
C9_CHARGED_DURATION_N,
C8_CHARGED_VOLUME_N,
C16_DISCOUNTED_VALUE_N,
round(C15_DISCOUNTED_AMOUNT_N/1000,4),
SYSDATE,
C13_CHRONO_NUM_N,
C6_ORGINATE_CELL_ID_V,
C3_STAGE_PROCESS_DATE,
'I' IND_UPDATE
from BIUSER.DIM_DATA_RECORD_TYPE DIM_DATA_RECORD_TYPE, BIUSER.DIM_DATE DIM_DATE, BIUSER.DIM_CALL_LOCATION DIM_CALL_LOCATION, BIUSER.DIM_APN DIM_APN, BIUSER.DIM_IMSI_MSISDN DIM_IMSI_MSISDN, BIUSER.DIM_TERM_CAUSE DIM_TERM_CAUSE, BIUSER.DIM_CALLCHARGE_TYPE_TB DIM_CALLCHARGE_TYPE_TB, BIUSER.DIM_TARIFF DIM_TARIFF, BIUSER.DIM_RATEPLAN DIM_RATEPLAN, BIUSER.C$_0FACT_ABIL_GPRS_T
where (1=1)
And (nvl(to_number(C14_SWITCH_CALL_TYPE_V),99999)=DIM_DATA_RECORD_TYPE.RECORD_TYPE)
AND (to_number(to_char(C12_CALL_DATE_DT,'RRRRMMDD'))=DIM_DATE.DIMDATEID)
AND (nvl(C11_MOBL_ORIGINATE_ZONE_CODE_V,'Undefined')=DIM_CALL_LOCATION.COUNTRY)
AND (nvl(C4_ACCESS_POINT_NAME_V,'Undefined')=DIM_APN.APN)
AND (nvl(C23_IMSI_NUM_N,99999999999)=DIM_IMSI_MSISDN.IMSI_NR)
AND (nvl(C20_CALL_TERMINATION_CAUSE_V,'XX')=DIM_TERM_CAUSE.TERMCAUSE)
AND (nvl(C18_CALL_CHRG_TYPE_V,'9')=DIM_CALLCHARGE_TYPE_TB.CALL_CHARGE_TYPE)
AND (nvl(C7_TARIFF_CODE_V,'999999')=DIM_TARIFF.TARIFF_CODE)
AND (nvl(C22_RATE_PLAN_CODE_N,99999)=DIM_RATEPLAN.RATEPLAN_CODE and
nvl(C7_TARIFF_CODE_V,'999999')=DIM_RATEPLAN.TARIFF_CODE)
minus
select
DIMDATASOURCEID,
DIMDATARECORDTYPEID,
DIMDATEID,
DIMTIMEID,
DIMAPNID_IC,
DIMIMSIID,
DIMCALLLOCATIONID,
DIMCAUSERECCLOSEID,
CALLDURATION,
UPLINK_DATAVOLUME,
DOWNLINK_DATAVOLUME,
CALL_CHARGE,
DIMRATEPLANID,
TRANS_DATE,
DIMPEAKID,
DIMTARIFFCODEID,
DIMCHARGEID,
MOBL_NUM,
ACC_LINK_CODE,
CHARGED_UNITS,
CHARGED_DURATION,
CHARGED_VOLUME,
DISCOUNTED_VALUE,
DISCOUNTED_AMOUNT,
FACT_PROCESS_DATE,
CHRONO_NUM,
ORIGINATE_CELL_ID,
STAGE_PROCESS_DATE,
'I' IND_UPDATE
from BIUSER.FACT_ABIL_GPRS_T -
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 Oracle function and Procedure using OCCI with in C++ code
Could any body send me the sample code to create and execute Oracle function and Procedure using OCCI concept in C++?.
Edited by: 788634 on Aug 16, 2010 4:09 AMHi Vishnu,
Yes, sure, you can create a PL/SQL procedure, function, package, package body, etc. from within an OCCI application. I would say that, generally, this is not the sort of activity a typical client application would perform unless there is some initialization/installation processes that need to happen. In any case, here is a simple demo showing how to create a stand alone procedure (in a real application I would use a package and body) that returns a ref cursor. The ref cursor is just a simple select of two columns in the hr.countries sample table. Of course, there is no error handling, object orientation, etc. in this demo - I wanted to keep the code as short and as simple as possible to illustrate the concept.
Regards,
Mark
#include <occi.h>
#include <iostream>
using namespace std;
using namespace oracle::occi;
int main(void)
// occi variables
Environment *env;
Connection *con;
Statement *stmt;
ResultSet *rs;
// database connection information
string user = "hr";
string passwd = "hr";
string db = "orademo";
// sql to create the procedure which returns a ref cursor as out parameter
// should be run as hr sample user or in a schema that has select privilege
// on the hr.countries table and a synonym (countries) that points to the
// hr.countries table
string sqlCreate =
"create or replace procedure get_countries(p_rc out sys_refcursor) as "
"begin"
" open p_rc for"
" select country_id, country_name from countries order by country_name; "
"end;";
// pl/sql anonymous block to call the procedure
string sqlCall = "begin get_countries(:1); end;";
// create a default environment for this demo
env = Environment::createEnvironment(Environment::DEFAULT);
cout << endl;
// open the connection to the database
con = env->createConnection(user, passwd, db);
// display database version
cout << con->getServerVersion() << endl << endl;
// create statement object for creating procedure
stmt = con->createStatement(sqlCreate);
// create the procedure
stmt->executeUpdate();
// terminate the statement object
con->terminateStatement(stmt);
// now create new statement object to call procedure
stmt = con->createStatement(sqlCall);
// need to register the ref cursor output parameter
stmt->registerOutParam(1, OCCICURSOR);
// call the procedure through the anonymous block
stmt->executeUpdate();
// get the ref cursor as an occi resultset
rs = stmt->getCursor(1);
// loop through the result set
// and write the values to the console
while (rs->next())
cout << rs->getString(1) << ": " << rs->getString(2) << endl;
// close the result set after looping
stmt->closeResultSet(rs);
// terminate the statement object
con->terminateStatement(stmt);
// terminate the connection to the database
env->terminateConnection(con);
// terminate the environment
Environment::terminateEnvironment(env);
// use this as a prompt to keep the console window from
// closing when run interactively from the IDE
cout << endl << "ENTER to continue...";
cin.get();
return 0;
} -
Call Oracle Function from ASP++++!
I have a lot of Oracle function in packages and i would like use it in my ASP pages.
With Oracle procedure it's all right.
Sample like this
set cn = Server.CreateObject("ADODB.Connection")
connString = "Provider=MSDAORA.1;Data Source=<>;User ID=<>;Password=<>"
cn.Open connString
SQL = "{call test.test_asp({resultset 0, cResult})}"
Set cmd = Server.CreateObject ("ADODB.Command")
Set cmd.ActiveConnection = cn
cmd.CommandText = SQL
cmd.CommandType = 1 'adCmdText
Set rs = Server.CreateObject ("ADODB.RecordSet")
Set rs = cmd.Execute
If NOT (rs.BOF and rs.EOF) Then
Do while NOT rs.EOF
<%=rs("dfcountry")%>
<%=rs("dfname")%>
rs.MoveNext
LOOP
End if
And in package TEST i have
PROCEDURE TEST_ASP(cResult IN OUT ResultCursor)
IS
BEGIN
OPEN cResult FOR
SELECT *
FROM tcountry;
END TEST_ASP;"
I Hope You help me with similar call a function!!!
For example, this is one
FUNCTION test_fun
RETURN resultcursor
IS
vres resultcursor;
BEGIN
OPEN vres FOR
SELECT *
FROM tcountry;
RETURN vres;
END test_fun;Stored Procedures
When executing an Oracle PL/SQL stored procedure using a command, use Oracle native syntax or the ODBC procedure call escape sequence in the command text:
Oracle native syntax: BEGIN credit_account(123, 40); END;
ODBC syntax: {CALL credit_account(123, 40)}
Preparing Commands
OraOLEDB validates and fetches the metadata only for SELECT SQL statements.
Command Parameters
When using Oracle ANSI SQL, parameters in the command text are preceded by a colon. In ODBC SQL, parameters are indicated by a question mark ("?").
OraOLEDB supports input, output, and input/output parameters for PL/SQL stored procedures and stored functions. OraOLEDB supports input parameters for SQL statements.
Joel P�rez -
Calling oracle function from Access passthrough query does not return list
Thanks to the help I received in an earlier post I've created an oracle 10g function that returns a list after executing the sql it contains. It works in oracle, using sql developer.
I need to have the list that it returns show up in MS Access via a passthrough query. It's not working so far. The connection string etc is ok, I'm able to use passthrough queries to run sql strings successfully. But when I try to call the function via the Access passthrough query at first nothing seems to happen (ie no list appears) and if I try to run it again, there is a odbc error 'call in progress. Current operation canceled'. There are only the three records in the table. I'm missing something, can anyone spot it?
The passthrough query looks like this
select * from fn_testvalues from dual
Again that runs in oracle.
To create the testing table and 2 functions see below.
CREATE TABLE t_values (MyValue varchar2(10));
Table created
INSERT INTO t_values (
SELECT 'Merced' c1 FROM dual UNION ALL
SELECT 'Pixie' FROM dual UNION ALL
SELECT '452' FROM dual);
3 rows inserted
CREATE OR REPLACE FUNCTION fn_isnum(p_val VARCHAR2) RETURN NUMBER IS
n_val NUMBER;
BEGIN
n_val := to_number(p_val);
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
Function created
testing the table:
SELECT val, fn_isnum(MyValue ) isnum
FROM t_values;
VAL ISNUM
Merced 0
Pixie 0
452 1
Now the function that is called in the passthrough query:
create or replace function fn_testvalues
return sys_refcursor is
rc sys_refcursor;
begin
open rc for
Select t_values.*, fn_isnum(MyValue) IsNum from t_values;
return(rc);
end fn_testvalues;lecaro wrote:
OK. But obviously there is some oracle object that one can call via an Access pass-through query which returns rows?Just to clarify. You could fetch data in Access from an Oracle function that returns a ref cursor using VBA editor. To use a pass-through query Oracle function should be a table function or pipelined table function:
CREATE OR REPLACE
TYPE testvalues_obj_type
AS OBJECT(
val varchar2(10),
isnum number
CREATE OR REPLACE
TYPE testvalues_tbl_type
AS TABLE OF testvalues_obj_type
CREATE OR REPLACE
FUNCTION fn_testvalues
RETURN testvalues_tbl_type
PIPELINED
IS
CURSOR testvalues_cur
IS
SELECT testvalues_obj_type(MyValue,fn_isnum(MyValue)) testvalues_obj
FROM t_values;
BEGIN
FOR v_rec IN testvalues_cur LOOP
PIPE ROW(v_rec.testvalues_obj);
END LOOP;
RETURN;
END;
/To test it in Oracle:
SELECT *
FROM TABLE(fn_testvalues)
VAL ISNUM
Merced 0
Pixie 0
452 1
SQL> Now in Access pass-trough query window enter:
SELECT *
FROM TABLE(fn_testvalues);SY. -
Calling Oracle Function in PHP
Hi,
I'm calling a oracle function in php, the function has 1 IN parameter and 1 OUT parameter. The OUT parameter is BOOLEAN type.How to bind php variable for BOOLEAN type?
Thanks.
srinath.I think you're going to have to use it as a string and use string comparison.
~Jer -
Toplink JPA Calling Oracle Function Return sys_refcursor
I have a function which return sys_refcursor and I am trying to call this using JPA(1.0)
@NamedNativeQuery( name = "getEmpsByDeptId"
, query = "{ ? = call my_pck.getEmployees(:longName)}"
, resultClass = Employee.class
, hints = { @QueryHint(name = "org.hibernate.callable", value = "true")
, @QueryHint(name = "org.hibernate.readOnly", value = "true")
DAOImpl
query = getEntityManager().createNamedQuery("getEmpsByDeptId");
query.setParameter("longName", "SCOTT");
list = (List<Employee>)query.getResultList();
However when I execute, I am getting the following exception
Exception [TOPLINK-6132] (Oracle TopLink Essentials - 2.1 (Build b52-fcs (09/24/2008))):
oracle.toplink.essentials.exceptions.QueryException Exception Description:
Query argument 2 not found in list of parameters provided during query execution.
Query: ReadAllQuery(test.entity.Employee) at oracle.toplink.essentials.exceptions.QueryException.namedArgumentNotFoundInQueryParameters
I have tried using
call my_pck.getEmployees(?)}"
and
query.setParameter(1, "SCOTT");
However error remains the same and how can I resolve this issue?
I have used the same function with Hibernate using JPA2.0 and it has worked.
Thanklecaro wrote:
OK. But obviously there is some oracle object that one can call via an Access pass-through query which returns rows?Just to clarify. You could fetch data in Access from an Oracle function that returns a ref cursor using VBA editor. To use a pass-through query Oracle function should be a table function or pipelined table function:
CREATE OR REPLACE
TYPE testvalues_obj_type
AS OBJECT(
val varchar2(10),
isnum number
CREATE OR REPLACE
TYPE testvalues_tbl_type
AS TABLE OF testvalues_obj_type
CREATE OR REPLACE
FUNCTION fn_testvalues
RETURN testvalues_tbl_type
PIPELINED
IS
CURSOR testvalues_cur
IS
SELECT testvalues_obj_type(MyValue,fn_isnum(MyValue)) testvalues_obj
FROM t_values;
BEGIN
FOR v_rec IN testvalues_cur LOOP
PIPE ROW(v_rec.testvalues_obj);
END LOOP;
RETURN;
END;
/To test it in Oracle:
SELECT *
FROM TABLE(fn_testvalues)
VAL ISNUM
Merced 0
Pixie 0
452 1
SQL> Now in Access pass-trough query window enter:
SELECT *
FROM TABLE(fn_testvalues);SY.
Maybe you are looking for
-
JAVA API to add header and footer in MS Word
Hi, please help me out, I am hanging with this concept. The problem is I need to add a headers in ms word file using java. I come to know that the API is support for this task is 1.apache POI 2.jacob I dont know which class file I need to use to do t
-
System Message "Multiple reports views are not permitted"
Hi All, followed previous thread with this error but didn't seem to get anywhere, so thought I'd raise a separate Thread. I'm designing a crystal report in Crystal Reports Developer Edition XI and trying to view the report with the addon in 2007A PL4
-
Determine if current component is being pulled in by paragraph reference?
Is there a way to determine at the component level if the current component is currently being imported into a paragraph reference component? A simple example would look like this in the component's jsp: if (/* Being Referenced */) { out.write("
-
How to install same DW cd on diff. pc's
I have an old laptop and a new desktop. I'm concerned that my laptop, which is already giving the occassional problem, will pack in altogether. Therefore, can I use the DWMX 2004 CD that I installed on my laptop onto my desktop? I don't wasnt to dele
-
I have just upgraded from 10.4.11 where the iPhone synched perfectly. Now using 10.5.4 and when I connect the phone Image Capture opens but not iTunes. I can download the pictures. iPhone appears in the System Profile as connected to the appropriate