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 AM
Hi 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;
}
Similar Messages
-
Calling Oracle Functions and Procedures in Java
I've looked online for a blurb on using Oracle SQL functions and
procedures in Java, but I haven't found anything. Can someone
either give me a quick crash course on this, or point me to the
best source of information for this?From the SQLJ FAQ.
http://otn.oracle.com/tech/java/sqlj_jdbc/htdocs/faq.html#sqljplsql
Within your SQLJ statements, you can use PL/SQL anonymous blocks
and call PL/SQL stored procedures and stored functions, as in the
following examples: Anonymous
block:
#sql {
DECLARE
n NUMBER;
BEGIN
n := 1;
WHILE n <= 100 LOOP
INSERT INTO emp (empno) VALUES(2000 +
n);
n := n + 1;
END LOOP;
END
Stored procedure call (returns the maximum
deadline as an output parameter into an output host expression):
#sql { CALL MAX_DEADLINE(:out maxDeadline) };
Stored function call (returns the maximum
deadline as a function return into a result expression):
#sql maxDeadline = { VALUES(GET_MAX_DEADLINE)
Of course, you can also use JDBC code to achieve the same - the
standard JDBC escape sequences for stored function and procedure
calls are supported, using for example:
"{? = CALL GET_MAX_DEADLINE}"
or:
"{call MAX_DEADLINE(?)}"
and for the rest of the details, get that JDBC crash course... -
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] -
Getting all Functions and Procedures using DBA_ARGUMENTS
Hi All
I am wanting to find out all functions and procedures that are within each of my packages and am using the following SQL to do this.
SELECT DISTINCT A.OBJECT_NAME, A.PACKAGE_NAME,
DECODE(POSITION,0,'FUNCTION','PROCEDURE')
FROM DBA_ARGUMENTS A
WHERE OWNER = 'NB'
I have discovered however that if a procedure has been overloaded with function will appear twice: as procedure and as a function
I was wondering if there was any workaround for this as I would only like a function to be displayed once?
Kind Regards
MarkThere is an 'OVERLOAD' column which can be used to show only specific overloads (e.g. first).
Determining which overload should be displayed in any given case may require some more thought. -
How to call package function and procedure by PL/SQL
Dear all,
I created a package and I want test it by a select statement. e.g. select packagename.function(1, 'A') . However, there is an error message. "ORA-14551: cannot perform a DML operation inside a query ".
In the package, there is a function and I passed two parameters to the function and return a number. These two parameters will be used in the cursor select statment. Is there sth wrong that I use the cursor with the parameters? What can I do then?
On the other hand, I want to test the package procedure by using select statement in SQL Plus. How can I call it (with parameter)?
Remark: I am using Oracle 8i.
Thanks for advance!!
Regrads.Hi!
I don't know why it is not running in ur computer. Pls check the script --
SQL> ed
Wrote file afiedt.buf
1 create or replace package pack_test
2 is
3 function try_test(eno in number,depno in number)
4 return number;
5* end;
SQL> /
Package created.
SQL> create or replace package body pack_test
2 is
3 function try_test(eno in number,depno in number)
4 return number
5 is
6 saln number(10);
7 begin
8 select sal
9 into saln
10 from emp
11 where empno = eno
12 and deptno = depno;
13
14 return saln;
15 end;
16 end pack_test;
17 /
Package body created.
SQL>
SQL> select pack_test.try_test(7777,30) from dual;
PACK_TEST.TRY_TEST(7777,30)
3456-it is working fine in my system.
Regards.
Satyaki De. -
Can SQL Developer control versioning of stored functions and procedures?
Hi all. I have a problem with my project, for developing Oracle functions and procedures. My team want to control versioning of that.
I found that Oracle SQL Developer support versioning features with CVS and Subversion. But I think it just about the files not functions and procedures.
We don't want to control version of files and copy it to stored somethings..
Do you have any idea?
Thanks for reading this post.Since K asked :)
Both SQL Navigator and Toad for Oracle support controlling PL/SQL at the FILE and DATABASE level.
[Controlling Objects in the Database with Toad|http://www.toadworld.com/BLOGS/tabid/67/EntryID/136/Default.aspx] -
Oracle Form functions and procedures in APEX, how?
I am working to recreate in APEX, already existing Read Only Forms in Oracle Forms. APEX Interactive Report functionality among other things, makes it worth while as well as targetting a different audience than the one that utilizies the Oracle Form versions. Oracle Forms versions use lots of pre and post query triggers, PLSQL Functions.
In Oracle Forms one of the places those functions can be located is in the "Program Units" section of the Form. A typical function of this sort, based on a specific Mission ID Itinerary, collects scheduled passengers last names, formats them with a comma and space after each one, into a single string that is returned and displayed as the passenger list of one row.
I have all this code written so I can move most of the main query of the Oracle Form into an Interactive Report. These functions and triggers called from within the Form, from the "Program Units" section of the Oracle Form rather than being stored in the Database schema in a package, where would they go inside APEX? Can I create a "Shortcut" in APEX and call it from the Interactive Report "Region Source"? Can I create the PLSQL function at the page level or region level of the Interactive Report? Or, is my best bet creating a package stored in the database, of all these functions and/or proecedures I may need from the original Oracle Form?
Some advice would be greatly appriciated.RLBickham wrote:
I don't think I have been clear enough in describing the specific thing I want to do, it simply does not reach the level of forms to APEX conversion. It is basically a PLSQL Function problem.
I have an Interactive Report that is currently getting 90 percent of what I want however, each row, representing a Mission may have multiple legs. Each Leg has two locations or ICAO codes attached to it. Based on the Mission number, I want to loop through the leg table, collect all the ICAO codes for that Mission, put them all into 1 variable separated by a coma and add that variable to the column display of that Interactive Report as the last column.
In Oracle Forms I have a function saved to the database that is called within the main query. Maybe I am asking a question that does not need to be asked but in any case my question is can I put that function currently in the database somewhere in the confines of the Interactive Report and reference it via Http somehow or should I just stick with putting functions and procedures in packages stored in the database and called the conventional way?You could move the function to the database and call it from the report query, but it sounds as if it's superfluous. In the report query use whatever form of Re: 4. How do I convert rows to columns? is appropriate to your (unspecified) database version.
When you have a problem you'll get a faster, more effective response by including as much relevant information as possible upfront. This should include:
<li>Full APEX version
<li>Full DB/version/edition/host OS
<li>Web server architecture (EPG, OHS or APEX listener/host OS)
<li>Browser(s) and version(s) used
<li>Theme
<li>Template(s)
<li>Region/item type(s) (making particular distinction as to whether a "report" is a standard report, an interactive report, or in fact an "updateable report" (i.e. a tabular form)
With APEX we're also fortunate to have a great resource in apex.oracle.com where we can reproduce and share problems. Reproducing things there is the best way to troubleshoot most issues, especially those relating to layout and visual formatting. If you expect a detailed answer then it's appropriate for you to take on a significant part of the effort by getting as far as possible with an example of the problem on apex.oracle.com before asking for assistance with specific issues, which we can then see at first hand. -
Using OCCI with Oracle XA Library
Is it possible to use OCCI with Oracle XA Library?
the XA function xaoSvcCtx() can returns the OCI service handle
for a given XA connection. but how to convert it to the OCCI
Connection class?
any comments would appreciate
RayHi Ravi,
We are now building CORBA application with C++. some programs
manage transaction through Transaction service(a TM of X/OPEN
DTP architecture), these programs must use XA Library.
OCCI is a wonderful tool for C++ programer,with OCCI building
a persistent layer over ORACLE is very simple.
But if OCCI not work with XA we have no choice but PRO*C or
OCI ,which's actually C style tool and hard to use especially
in object mode.
So we hope OCCI can provide this feature in next release. and
I beleive This feature is necessary,It's very common using a
transaction monitor such as ORACLE Application Server .
regards,
Ray -
Double quotes in function and procedure names when using impdp
When viewing a function in the original database, it looks like:
CREATE OR REPLACE FUNCTION TA_ACTIVITY_D_GEN_FNC
After doing an expdp and impdp to restore a development database, it now looks like
CREATE OR REPLACE FUNCTION "TA_ACTIVITY_D_GEN_FNC"
and also has 2 blank lines at end of function.
This causes us problems when trying to use various utilites to compare differences in production and development. Now every function and procedure shows up as being different.
Can someone please explain why and what can be done to avoid this from happening?
Edited by: user6116705 on Jun 15, 2010 7:52 AMfrom old exp, here is the first line of the create procedure statement:
CREATE FORMAT71 PROCEDURE "SECURE_DML"
You can see the double quotes. I don't understand why you wouldn't see the same compare issue with old exp. I was wondering what you were using for compare since it would let me know where to look for anything that has changed from the original create to the create performed by data pump. I remember there being an issue in this area. I just don't remember if it was extra spacing, upcasing, or something else or multiple changes. You could contact Oracle support to see if there is a fix and if it is backported to your version.
The only other way you can possibly fix this (and it would be a huge pain) would be to run impdp with a sqlfile and then edit the sqfile to remove the double quotes and to remove any extra spacing/extra lines. A patch from Oracle would certainly be easier if one was available.
Dean -
RoR Calling Oracle Function/Procedure
Hello,
Has anyone got experience of calling an Oracle Function or Procedure from RoR?
thanks
DavidHello for calling function/procedure at RoR in Oracle I write muself classes and use they.
Module:
module SQLStatement
class NoTypeResult < StandardError
end # class
class SQLProc
attr_accessor :name, :arguments
def initialize( args = nil )
@name = args[:name] unless args[:name].nil?
@arguments = args[:arguments] unless args[:arguments].nil?
@conn = ActiveRecord::Base.connection.raw_connection
end # def initialize
def exec( args = nil )
unless args.nil? || ( !args.is_a? Hash )
args.each { |k, v| @arguments[k.to_s.intern] = args[k] }
end # unless
func_args = ''
@arguments.each { |k, v| func_args += "#{func_args == '' ? '' : ', '}#{k.to_s} => :#{k.to_s}"}
sql = "BEGIN {#@name}( #{func_args} );END;"
cursor = @conn.parse( sql )
@arguments.each do |k, v|
cursor.bind_param( ":#{k.to_s}", v )
end # each
cursor.exec()
end # def exec
end # class SQLProc
class SQLFunc < SQLProc
attr_reader :result
attr_accessor :result_type
def initialize( args = nil )
@result_type = args[:result_type] unless args[:result_type].nil?
super( args )
end # def
def exec( args = nil )
if @result_type.nil?
raise NoTypeResult, 'No type for result setting', caller
end # if
unless args.nil? || ( !args.is_a? Hash )
args.each { |k, v| @arguments[k.to_s.intern] = args[k] }
end # unless
func_args = ''
@arguments.each { |k, v| func_args += "#{func_args == '' ? '' : ', '}#{k.to_s} => :#{k.to_s}"}
sql = "BEGIN :result := #{@name}( #{func_args} );END;"
cursor = @conn.parse( sql )
@arguments.each do |k, v|
cursor.bind_param( ":#{k.to_s}", v )
end # each
cursor.bind_param( ":result", nil, @result_type )
cursor.exec()
@result = cursor[':result']
cursor
end # def exec
end # class
end # module SQLStatment
Example of use:
function = SQLStatement::SQLFunc.new(
:name => 'f_test_ins',
:result_type => Fixnum,
:arguments => {
:login =>'asdf',
:password => 'asdf',
:email => '[email protected]'
function.exec
raise function.result.inspect -
How to run the Oracle Triggers,Functions and Procedures from java
Hi ,
I want to execute the Oracle's Triggers, Functions and Procedures from java as like executing the SQL commands by using Execute statements.
Or can we have some other option for doing this.
Plz help me ...you can use CallableStatement interface of JDBC to execute any DBMS triger,stored procedure ....
refer any of the JDBC book for extra help
hope you got it
Azeem Ahmed -
How to use type, packages, functions, and procedures in another schema ?
I have two target schema in one OWB project, such as A and B. In a mapping of A, I would like to use some types, packages, functions, and procedures from B. I have tried the method of synonym as suggested, but I could not find the metadata of these when importing ... The only type of synonym I can import is the synonym for table. Is there a bug for synonym?
If I cannot use synonym for this issue, is there another way to solve the problem?Now, in some instances you will absolutely need to create the second module as Carsten describes, however it should also be noted that you can reference objects in things like Expressions even if you have not loaded up the metadata. It is only when you need strong binding that it becomes neccessary to import objects. For everything else, as long as the reference will resolve at compile-time then you are good to go.
For example, I have a function in one target schema (S1) and a private synonym to it in another(s2). A mapping in the S2 schema has an expression object that uses the synonym to the function in the expression property for a couple of the output attirbutes. The synonym has not been loaded into metadata - indeed OWB has no knowledge of its existance. But it resolves at compile time so the mapping validates and generates successfully.
Mike -
Use of function and procedures
when we need to use function rather than procedure or viceversa???
Welcome to the forum!
Use a function if you want to use the value it returns as you would use any other expression in a SQL statement:
SELECT SYSDATE
, my_function (column1) AS c1
, UPPER (column2) AS c2
FROM table_x;or in PL/SQL:
IF my_function (x) > 0 THEN ...Use a procedure otherwise; for example, if there is no value to be passed back.
Functions can have OUT (and IN OUT) arguments, but they can cause confusion. Many people use procedures whenever they need OUT arguemnts, which includes all situations where 2 or more values are passed back.
Any good book or site on PL/SQL, or any kind of procedural programming, should explain the differences between functions and procedures.
If you don't have at least that much guidance, it's better not to try using PL/SQL. -
I m also trying for How to pass Object to a procedureb using OCCI...
Steps....
1. I created A type.....
2. Then I created a VARRAY using that Type.
3.After that I have written An Procedure with object as a parameter..
now using OCCI how do u bind the parameter with this . plz note that using OTT
i have already created the class representation of above object type i.e class
four Files Created 1> demo.h 2>registermapping.h
3> demo.cpp 2>registermapping.cpp
After I want to Pass the Values in A Vector...
vctor<full_name *> vect;
stmt=con->createStatement("BEGIN Add_Object(:1); END;");
full_name *name1 = new full_name; //Giving the Error here Given below....
name1->
name1->
Through name1 Which Function I will call in which I will Pass a String....
like
name1->readSQL("Sanjay"); Or I have to add a function......
vect.push_back(name1);
setVector(stmt,1,vect,"FULL_NAME");
error C2259: 'FullName' : cannot instantiate abstract class
can u plz suggest me Why this Error is Giving......?
How to pass the data?
setFirst_name() and setLast_name() this two function I will add in Demo.cpp which one created automativcally by Using OTT command.....or other way plz tell me Boss ....
Can u lz Suggest me ASAP....hi Nishant ,
What u have done Now I mm trying ....
can u Plz Suggest me......
How to pass and Array of Object in Procedure using OCCI... Doing....
90% finished Two Error's Are Coming...
1> If I create the Class then Data Not Inserting table......
2> If I will create the Class through OTT command.......
then U can't Instantiate Object It is DIsplying ,this is Abstract Class(PObject)...
Beco'z the below Method is Not adding Automatically by OTT command which is Pure Virtual Function.....
But I added this Function Still SAme Error Giving..
getSQLTypeName(oracle::occi::Environment env, void *schName,
unsigned int &schNameLen, void **typeName,
unsigned int &typeNameLen) const
Plz Suggest me....
regard's
sanjay -
Exact difference between function and procedure
exact difference between function and procedure(real time diff.....not like return value, dml....) and function do some work at the same time that work also do procedure..why function
ranitB wrote:
1. Function is called Inline a query. A return value is must.
But, procedure may/may not contain a return value.Not true.
A function may be called in a query providing it meets certain limitations (no DDL, or transactional statements such as commit/rollback etc.).
A function does not have to be called from a query, it can be called from other PL/SQL code or from other external applications.
Regular functions must return a value, though pipelined functions do not...
SQL> CREATE OR REPLACE TYPE split_tbl IS TABLE OF VARCHAR2(32767);
2 /
Type created.
SQL> CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_delim VARCHAR2:=' ') RETURN SPLIT_TBL PIPELINED IS
2 l_idx PLS_INTEGER;
3 l_list VARCHAR2(32767) := p_list;
4 l_value VARCHAR2(32767);
5 BEGIN
6 LOOP
7 l_idx := INSTR(l_list, p_delim);
8 IF l_idx > 0 THEN
9 PIPE ROW(SUBSTR(l_list, 1, l_idx-1));
10 l_list := SUBSTR(l_list, l_idx+LENGTH(p_delim));
11 ELSE
12 PIPE ROW(l_list);
13 EXIT;
14 END IF;
15 END LOOP;
16 RETURN;
17 END SPLIT;
18 /
Function created.
SQL> SELECT column_value
2 FROM TABLE(split('FRED,JIM,BOB,TED,MARK',','));
COLUMN_VALUE
FRED
JIM
BOB
TED
MARK... whilst the definition of the function shows a return type, the return statement inside the function simply returns, without a value. That's because the data is passed back through a special "pipeline", and you can write code to show that the data is available to a query as soon as it's piped, and before the function has completed (reached the return statement) if you like.
A procedure does not return a value (And no an OUT parameter is not a "returned" value, it's a writeable parameter, there's a difference)
2. There are some limitations in functions which is possbl through procedures.
Like - Oracle doesn't support DML in functions called in Select queries (using PRAGMA AUTONOMOUS_TRANSACTION will help).Not strictly true. and SQL query is considered to be DML, so a function could perform a query and then be used inside another query...
SQL> ed
Wrote file afiedt.buf
1 create or replace function f_dname(p_deptno in number) return varchar2 is
2 v_dname varchar2(10);
3 begin
4 select dname into v_dname
5 from dept
6 where deptno = p_deptno;
7 return v_dname;
8* end;
SQL> /
Function created.
SQL> ed
Wrote file afiedt.buf
1* select empno, ename, f_dname(deptno) as dname from emp
SQL> /
EMPNO ENAME DNAME
7369 SMITH RESEARCH
7499 ALLEN SALES
7521 WARD SALES
7566 JONES RESEARCH
7654 MARTIN SALES
7698 BLAKE SALES
7782 CLARK ACCOUNTING
7788 SCOTT RESEARCH
7839 KING ACCOUNTING
7844 TURNER SALES
7876 ADAMS RESEARCH
7900 JAMES SALES
7902 FORD RESEARCH
7934 MILLER ACCOUNTING
14 rows selected.It's been discussed many times on the forum... my favourite here...
{message:id=1668675}
Edited by: BluShadow on 17-Sep-2012 09:22
Maybe you are looking for
-
Copied view not displaying, in icwebclient
Hi All, In IC Webclient, I have copied standard view and made changes to it. I have also done ic webclient profile customization. But then also , standard view ia coming. If anyone worked on IC webclient pls help Thanks Hemalatha
-
Missing "illustrations" tab and read-only information
After a Windows XP Home repair, no illustration tab and read-only information by new music downloads. Have most recent itunes. Can someone help me...please?
-
Extending the Resource XML Schema XDBResource.xsd
Hi, Is anybody could share an expirience about extending the Resource XML Schema XDBResource.xsd ? I want to use XML DB as document repository. I want to use some application parameters (for example document varchar id and so on) as resource properti
-
Some tunes not found when sync?
I am unable to tranfer some songs from itune playlists to my white iphone4, I keep getting the message that some tracks were not found. I also have a black iphone4, and all sync works well, I am using the same computer for both phones, Any ideas??? T
-
Getting "an error occurred while backing up this iPad (-5000).
I am getting an error when trying to update my wifes gen1 iPad from 4.2.1 to whatever is the latest: "An error occurred while backing up this iPad (-500). Would you like to continue to update this iPad? Continuing will result in the loss of all conte