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...
Similar Messages
-
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;
} -
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 -
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] -
Calling Oracle Export and Import in java
Hi,
I am trying to call oracle export and import utilites in my java application,
can anyone help me that how can i do this, plz consider the case as this is a part of my project..
Regards
AshishYou should just be able to call the "imp" and "exp" executables ($ORACLE_HOME/bin) using the Runtime class. You can setup the various parameters for export / import in a parameter file.
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
http://www.orafaq.com/faqiexp.htm -
Call stored function / stored procedure from JAVA/JPA and pass array
I fail calling a plsql function from java with jpa - it works perfect without the array but its not working with the array:
PLSQL Function:
function getHtml(pWhere VARCHAR2 DEFAULT NULL,
pColSort HTP.STRINGARRAY) return clob is
begin
errorhndl.Log(pMessage => 'called');
htp.prn('das ist der test
for i in 1 .. pColSort.count loop
htp.p('
pColSort['||i||']: '||pColSort(i));
end loop;
htp.prn('
<table> <tr> <td> max1.0 </td> <td> max2.0 </td> </tr>');
htp.prn('<tr> <td> max1.1 </td> <td> max2.1 </td> </tr> </table>');
htp.prn('test ende');
return htp.gHtpPClob;
exception
when others then
null;
end getHtml;
PLSQL TYPE: (in HTP package - self created - but could be anywhere else too)
type STRINGARRAY is table of varchar2(256) index by binary_integer;
JAVA DOA:
public class ShowReportDOAImpl implements ShowReportDOA {
private JdbcTemplate jdbcTemplate;
private SimpleJdbcCall procShowReport;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
procShowReport = new SimpleJdbcCall(this.jdbcTemplate)
.withCatalogName("Show_Report")
.withFunctionName("getHtml")
.withoutProcedureColumnMetaDataAccess()
.declareParameters(
new SqlParameter("pWhere", Types.VARCHAR),
new SqlParameter("pColSort", Types.ARRAY, "HTP.STRINGARRAY"),
new SqlOutParameter("RETURN", Types.CLOB)
public String readReport(Long id, ParameterHelper ph) {
String[] sortCol = {"max", "michi", "stefan"};
String pWhere = "fritz";
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("pWhere", pWhere);
parms.addValue("pColSort", sortCol, Types.ARRAY, "HTP.STRINGARRAY");
parms.addValue("pColSort", Arrays.asList(sortCol), Types.ARRAY, "HTP.STRINGARRAY");
Clob clob = procShowReport.executeFunction(Clob.class, parms);
String clobString = "";
try {
System.out.println("length: "+new Long(clob.length()).intValue());
clobString = clob.getSubString(1, new Long(clob.length()).intValue());
} catch (SQLException e) {
e.printStackTrace();
return clobString;
EXCEPTION IS:
org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{? = call SHOW_REPORT.GETHTML(?, ?)}]; SQL state [null]; error code [17059]; Konvertierung zu interner Darstellung nicht erfolgreich: [max, michi, stefan]; nested exception is java.sql.SQLException: Konvertierung zu interner Darstellung nicht erfolgreich: [max, michi, stefan]
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:969)
org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1003)
org.springframework.jdbc.core.simple.AbstractJdbcCall.executeCallInternal(AbstractJdbcCall.java:391)
org.springframework.jdbc.core.simple.AbstractJdbcCall.doExecute(AbstractJdbcCall.java:354)
org.springframework.jdbc.core.simple.SimpleJdbcCall.executeFunction(SimpleJdbcCall.java:154)
at.ontec.cat.config.doa.ShowReportDOAImpl.readReport(ShowReportDOAImpl.java:47)
at.ontec.cat.http.ShowReport.doGet(ShowReport.java:80)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause
java.sql.SQLException: Konvertierung zu interner Darstellung nicht erfolgreich: [max, michi, stefan]
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:124)
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:161)
oracle.jdbc.driver.DatabaseError.check_error(DatabaseError.java:860)
oracle.sql.ARRAY.toARRAY(ARRAY.java:209)
oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:7767)
oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7448)
oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7836)
oracle.jdbc.driver.OracleCallableStatement.setObject(OracleCallableStatement.java:4586)
org.apache.commons.dbcp.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:166)
org.apache.commons.dbcp.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:166)
org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:356)
org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:216)
org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:127)
org.springframework.jdbc.core.CallableStatementCreatorFactory$CallableStatementCreatorImpl.createCallableStatement(CallableStatementCreatorFactory.java:212)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:947)
org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1003)
org.springframework.jdbc.core.simple.AbstractJdbcCall.executeCallInternal(AbstractJdbcCall.java:391)
org.springframework.jdbc.core.simple.AbstractJdbcCall.doExecute(AbstractJdbcCall.java:354)
org.springframework.jdbc.core.simple.SimpleJdbcCall.executeFunction(SimpleJdbcCall.java:154)
at.ontec.cat.config.doa.ShowReportDOAImpl.readReport(ShowReportDOAImpl.java:47)
at.ontec.cat.http.ShowReport.doGet(ShowReport.java:80)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
Please help!!
Please help!!user8374822 wrote:
PLSQL Function:
function getHtml(pWhere VARCHAR2 DEFAULT NULL,
pColSort HTP.STRINGARRAY) return clob is
begin
end getHtml;
PLSQL TYPE: (in HTP package - self created - but could be anywhere else too)
type STRINGARRAY is table of varchar2(256) index by binary_integer;
JAVA DOA:
new SqlParameter("pColSort", Types.ARRAY, "HTP.STRINGARRAY"),I don't know much (??) java and can't understand your error messages as they are not in english.
But I have a feeling that the error is because either
a) "Types.ARRAY" in Java world probably does not map to an index-by table in oracle or
b) the array must be created as a SQL TYPE and not as a package variable or
c) both of the above
You may want to try following approaches
1) Change the array type declaration to nested table i.e. use "type STRINGARRAY is table of varchar2(256)"
2) If the above does not work, then create a sql type (using CREATE TYPE statement) to create STRINGARRAY as a SQL type of varchar2(256)
Hope this helps. -
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. -
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 -
Calling oracle export and import utilities in java
Hi,
can someone help me, i have to call oracle export and import utilities through my java application, can anyone guide me, how i can do it..
Thansks
AshishHi,
can someone help me, i have to call oracle export and
import utilities through my java application, can
anyone guide me, how i can do it..You mean the command line ones? Use Runtime.exec(); -
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 -
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 -
Hi Friends,
My Question is : At what time we will use function and Procedure.? How i can prefer it?
Regards,
AnuFunctions are normally used for computations where as procedures
are normally used for executing business logic.
there can be many difference between stored procedures and functions
main are
1. function can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
If you have a function in which there are DML statements only then you can not call this function in a SQL query
for example
For example, if you have a function that is updating a table, you cannot call that function from a SQL query.
- select myFunction(field) from sometable; will throw error.
But you can do it through procedure.
I hope it is clear -
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
Maybe you are looking for
-
Create a new routing with BAPI BAPI_ROUTING_CREATE via JCo
I try to create a new routing with BAPI BAPI_ROUTING_CREATE via JCo. I filled all necessary parameters. I also realized a commit_work. I get in the RETURN parameter of the BAPI the Message "S 000 Routing N/50001641/01". But the routing isn't in the d
-
Deploy of 11.4.402.278 version with .MSI file
After the deploy of 11.4.402.278 version with .MSI file, the Controll panel, falsh 32, tab advanced shows the 11.4.402.278 version. in control panel, install e remove application, the Flash version is always the preview 11.4.402.267 version. So i c
-
Symbole aus Werkzeugleiste verschwinden nach Neustart / Acrobat 9
Hallo Community, ich habe folgende Problematik. Wenn ich persönliche Benutzereinstellungen in meiner Werkzeugleiste vornehme werden diese Einstellungen bei dem nächsten Start von Acrobat zurückgesetzt. Genauer, ich lass mir das "TouchUp-Leserichtungw
-
Not able to create StdSchedulerFactory due to missing my_quartz.properties
Hi , Below piece of code is returning NPE as it is not able to read my_quartz.properties from the context: factory =(org.quartz.impl.StdSchedulerFactory) ctx.getAttribute(QuartzInitializerServlet.QUARTZ_FACTORY_KEY); Here is the error <Sep 29, 2008 3
-
Adobe premiere elements 4 minimizes to taskbar upon opening?
Hi I use adobe premiere elements 4 and the minimizes to the taskbar and can't be maximized as soon as I try to start or open a project. I then have to right click and close to exit. Anyone have any idea why this is happening and how to fix it? I g