How to return a resultset in a stored procedure without using Cursor
Dear all,
I need to return a resultset in a stored procedure.
I know I can return a Cursor.
But because there are many complicate logics I need to carry out,
so I can finish all the logic in a SINGLE SQL select statement, so I think it can't
use Cursor as return value.
Does anybody know other approaches? Please help.
Thanks!
Some basic techniques that one can use in SQL. These are merely to illustrate (simplistically) different approaches.
> field3 = select count(*) from table2,table1 where table2.id = table1.id
This can be done via an analytical function (refer to the SQL Reference) or very simply, as an in-line select as follows:
SQL> select
2 o.object_name,
3 (select count(*) from user_objects u where u.object_type = o.object_type) as "ONE OF",
4 o.object_type
5 from user_objects o
6 where o.object_name = 'LISTFILES';
OBJECT_NAME ONE OF OBJECT_TYPE
LISTFILES 8 PROCEDURE
So LISTFILE is "one of 8" procedures. I would however rather so this via an analytic function as these are a lot more flexible. Note the WITH clause that allows "modularisation" of SQL - kind of like creating "sub-SQL results" in a single SQL statement:
SQL> with DATASET1 as(
2 select
3 object_name,
4 count(distinct object_name) over (partition by object_type) as TOTAL_TYPES,
5 object_type
6 from user_objects
7 ),
8 DATASET2 as(
9 select
10 name,
11 text as SOURCE_LINE,
12 line as LINE_NO,
13 count(line) over (partition by name) as TOTAL_LINES
14 from user_source
15 )
16 select
17 object_name,
18 '1 of '||total_types||' '||object_type as "TYPE",
19 source_line as "1st LINE",
20 total_lines as "TOTAL LINES"
21 from DATASET1 ds1,
22 DATASET2 ds2
23 where ds1.object_name = ds2.name
24 and ds1.object_name = 'LISTFILES'
25* and ds2.line_no = 1
SQL> /
OBJECT_NAME TYPE 1st LINE TOTAL LINES
LISTFILES 1 of 8 PROCEDURE procedure ListFiles( cDirectory in varchar2 ) 3
SQL>
SQL is quite powerful and analytical functions allows all kinds of aggregation processing per row, accessing the leading or lagging rows' data, etc.
You need to play around with this to get to grips with it and how to apply it.
Similar Messages
-
Invoking Stored procedures without using CallableStatement
I have a piece of code:
import java.sql.*;
public class Somenath{
public static void main(String args[])throws ClassNotFoundException,SQLException{
String abc;
String query="{ call PR_EXAMPLE_I(?,?) }";
String name="TEST FUND 2";
Connection con = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@172.16.31.120:1521:ora9db","gs2","gs2");
Statement statement=con.createStatement();
CallableStatement cs = con.prepareCall(query);
cs.registerOutParameter(2,Types.VARCHAR);
cs.setString(1,name);
cs.execute();
String nameval=cs.getString(2);
System.out.println("Name"+nameval);
try{
finally{
cs.close();
This code works fine.
I would like to know wheather its possible to execute a stored procedure using the
statement.execute()/statement.executeQuery().Please note as per Java's documentation statement.execute() may be used execute any unknown SQL String.So is it possible to execute a stored procedure thats already existing(say PR_EXAMPLE_I in the current example).Thank you Digital Dreamer for ur help.I will explain the problem in detail.
Well I wish to invoke a stored procedure that uses a in paramater but no out parameter.Assume that the stored procedure (say abc) already exists in the system.We execute a Select statement inside the Stored procedure and copy the value in a block-variable(a local one) within the Stored Procedure.
Usually we execute the stored procedure in the SQL Prompt using
SQL> exec Proc_Name(In Paramter)
I would like to know how do I do it in JDBC using Statement.(Please note that we are not using Callable Statement)
Can u help me out with an example? -
Newbie question on how to return java objects from java stored procedures
Hi,
As you may guess, i'm new to this.
I have a stored procedure that does some calculations and creates a list of java objects as the result of the query.
How would I return the list from the database to the client application?
Would I have to create an Oracle type that maps to the java object?
Please help.
JagHi Jag,
Your question is very vague (to me). Perhaps you could post what you have done so far? Have you tried looking through the Sample Code page of the Technet Web site, or tried searching the Ask tom Web site, or MetaLink?
Good Luck,
Avi. -
How to return List or Array from Web Service without using ADF?
All,
I would like to know how to do this before I use ADF. Sounds like a simple thing to do - common even - but I haven't found a solution in existing postings. My attempts have failed though I'm not sure exactly why.
I have created a declarative WS that takes a single parameter and tries to return a List<Employees> resultset. My Sample Java Client works just fine. When I change the result type from List to String[], for example, it also works fine.
What am I doing wrong??
Thanks
package wizard;
(imports removed for readability)
@WebService(name = "MyWebService1", serviceName = "MyWebService1", portName = "MyWebService1SoapHttpPort")
@Deployment(restSupport = true)
public class HelloWorld {
List<Employees> employees = null;
public HelloWorld() {
public List<Employees> sayHello (String s) {
try {
final Context context = getInitialContext();
ATOABPFacade aTOABPFacade = (ATOABPFacade)context.lookup("ATOABPFacade");
employees = aTOABPFacade.queryEmployeesFindByName(s);
return employees;
} catch (Exception ex) {
ex.printStackTrace();
return employees;
private static Context getInitialContext() throws NamingException {
return new InitialContext();
Trace:
Ready message received from Oc4jNotifier.
Embedded OC4J Server startup time: 24063 ms.
Target URL -- http://localhost:8988/JPA-Wizard-context-root/mywebservice1soaphttpport
Feb 18, 2008 7:42:49 PM com.evermind.server.ServerBase log
WARNING: JPA-Wizard-webapp: Error preloading servlet
javax.servlet.ServletException: java.lang.NullPointerException
at oracle.j2ee.ws.server.provider.ProviderServlet.init(ProviderServlet.java:186)
at javax.servlet.GenericServlet.init(GenericServlet.java:241)
at com.evermind.server.http.HttpApplication.loadServlet(HttpApplication.java:2674)
at com.evermind.server.http.HttpApplication.findServlet(HttpApplication.java:5162)
at com.evermind.server.http.HttpApplication.findServlet(HttpApplication.java:5085)
at com.evermind.server.http.HttpApplication.initPreloadServlets(HttpApplication.java:5275)
at com.evermind.server.http.HttpApplication.initDynamic(HttpApplication.java:1357)
at com.evermind.server.http.HttpApplication.init(HttpApplication.java:873)
at com.evermind.server.http.HttpApplication.<init>(HttpApplication.java:699)Gi,
not sure what you are doing there, but you can build the J2EE WebService from your working POJO, and create a Web Service proxy class from the WSDL description (of the deployed or local WSDL file). Then, using the proxy class, you can access the output of the WebService.
Frank -
Resultset from a Stored Procedure
Hello Everyone,
Is it possible to return a resultset from a stored procedure? I need to do display set of rows which are resulted by joining few tables.
Is it possible?
Please help..
TIA
Regards,
Rao Santapur.
null<BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by Raymond Tang ([email protected]):
You can use 'REF CURSOR'<HR></BLOCKQUOTE>
I have created a stored procedure with a ref cursor- what parameters do i need to pass via Sql*Plus to get results?
[email protected]
null -
Hi,
How do I return two values from a
stored procedure into an "Execute SQL Task" please? Each of these two values need to be populated into an SSIS variable for later processing, e.g. StartDate and EndDate.
Thinking about stored procedure output parameters for example. Is there anything special I need to bear in mind to ensure that the SSIS variables are populated with the updated stored procedure output parameter values?
Something like ?
CREATE PROCEDURE [etl].[ConvertPeriodToStartAndEndDate]
@intPeriod INT,
@strPeriod_Length NVARCHAR(1),
@dtStart NVARCHAR(8) OUTPUT,
@dtEnd NVARCHAR(8) OUTPUT
AS
then within the SSIS component; -
Kind Regards,
Kieran.
Kieran Patrick Wood http://www.innovativebusinessintelligence.com http://uk.linkedin.com/in/kieranpatrickwood http://kieranwood.wordpress.com/Below execute statement should work along the parameter mapping which you have provided. Also try specifying the parameter size property as default.
Exec [etl].[ConvertPeriodToStartAndEndDate] ?,?,? output, ? output
Add a script task to check ssis variables values using,
Msgbox(Dts.Variables("User::strExtractStartDate").Value)
Do not forget to add the property "readOnlyVariables" as strExtractStartDate variable to check for only one variable.
Regards, RSingh -
Returning a table from a stored procedure
hi, i need to return a table from a stored procedure and show it, and come to this, but a don't know hoy to run it, so i don't know if it is right, can anyone help me?
uTable out objects_uptime%rowtype
as
begin
select * into uTable from objects_uptime;
end;well, i finally discovered how to do the trick
this is the code for the function:
CREATE OR REPLACE FUNCTION FN_GET_RECORDS RETURN UPTIME PIPELINED IS
CURSOR cUptime is select * from objects_uptime;
p refcur.refcur_t;
temp p%ROWTYPE;
temp2 OUPTIME := OUPTIME(null, null, null, null, null, null, null, null, null);
BEGIN
OPEN cUptime;
LOOP
FETCH cUptime into temp;
temp2.OBJ_NAME := temp.OBJ_NAME;
temp2.IP := temp.IP;
temp2.STATUS := temp.STATUS;
temp2.DOE := temp.DOE;
temp2.ENABLED := temp.ENABLED;
temp2.COMMENT00000 := temp.COMMENT00000;
temp2.USERID := temp.USERID;
temp2.OBJECTID := temp.OBJECTID;
temp2.MNTID := temp.MNTID;
pipe row(temp2);
EXIT WHEN cUptime%NOTFOUND;
END LOOP;
RETURN;
END FN_GET_RECORDS;
and this for the auxiliar package, object and table:
CREATE OR REPLACE PACKAGE REFCUR
as
TYPE refcur_t IS REF CURSOR RETURN objects_uptime%ROWTYPE;
end REFCUR;
CREATE OR REPLACE TYPE OUPTIME AS OBJECT ( "OBJ_NAME"
VARCHAR2(255), "IP" VARCHAR2(20), "STATUS" VARCHAR2(10),
"DOE" DATE, "ENABLED" NUMBER(10, 1), "COMMENT00000"
VARCHAR2(1000), "USERID" VARCHAR2(50), "OBJECTID" NUMBER(10,
1), "MNTID" NUMBER(10, 1) )
CREATE TYPE TUPTIME AS
TABLE OF OUPTIME
i call it this way:
select * from table(FN_GET_RECORDS ())
if anyone knows how to do the same in a shorter manner, tell me please.
thanks to everybody for the help. -
How to create a stored procedure and use it in Crystal reports
Hi All,
Can anyone explain me how to create a stored procedure and use that stored procedure in Crystal reports. As I have few doubts in this process, It would be great if you can explain me with a small stored proc example.
Thanks in advance.If you are using MSSQL SERVER then try creating a stored procedure like this
create proc Name
select * from Table
by executing this in sql query analyzer will create a stored procedure that returns all the data from Table
here is the syntax to create SP
Syntax
CREATE PROC [ EDURE ] procedure_name [ ; number ]
[ { @parameter data_type }
[ VARYING ] [ = default ] [ OUTPUT ]
] [ ,...n ]
[ WITH
{ RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION } ]
[ FOR REPLICATION ]
AS sql_statement [ ...n ]
Now Create new report and create new connection to your database and select stored procedure and add it to the report that shows all the columns and you can place the required fields in the report and refresh the report.
Regards,
Raghavendra
Edited by: Raghavendra Gadhamsetty on Jun 11, 2009 1:45 AM -
How to pass the parameter of a stored procedure to iReport
Hi... i don't know how to pass the parameter of the stored procedure to the iReport.
In the Report Query, i tried
1. sp_storedprocedure ' value'
2. sp_storedprocedure +''''+$P{parameter}+''''+
3. sp_storedprocedure +$V+$P{parameter}++$F($F is a variable having a value of ' (a single quote))may you enlighten us please? thank youFor M$ SQL server I find that it only works when U use the fully qualified name...
e.g. catalod.dbo.my_procedure_name 'variable'
My full query in the Report Query window is something like this:
EXEC arc.dbo.jasper_Invoice 1000
Note that you may find that selecting from VIEWS / TABLES fails for no apparent reason and iReport will prompt you with the usual very unhelpful (we have what we "pay" for) prompt, stating that "The document is empty".
To work around this issue, where a statement like "SELECT * FROM arc.dbo.acc_invoices WHERE Invoice_id=1000" does not work, simply create a PROC, something like:
CREATE PROC jasper_MyProc (@my_rec_id integer) AS
SELECT * FROM arc.dbo.acc_invoices WHERE Invoice_id= @my_rec_id integer
...to wrap your SELECT statement, then call the PROC
Edited by: Sylinsr on Apr 22, 2008 4:23 PM -
How to execute multiple queries in one stored procedure.
Hi,
I am Kumar,
How to execute multiple queries in one stored procedure.
here is the my requirements,
1. get the max value from one table and sum of the that value.
2. insert the values and also sum of the max value.
using stored procedure
I am using SQL server 2000 database.
Please help me.
Advance thanks
by,
KumarThis is not a java question and it is not even a problem: your only problem is
1) lack of knowledge
2) lack of interest to find a manual
But you are going to have to change both by actually reading a book or a manual that explains the stored procedure language of SQL Server. It is the same as Sybase I think, so you could also look for a manual for that DBMS. -
How to create stored procedures and use those in Crystal reports
Hi All,
Can anyone explain me how to create a stored procedure and use that stored procedure in Crystal reports. As I have few doubts in this process, It would be great if you can explain me with a small stored proc example.
Thanks in advance.Hello,
There is a document explainining how to use Oracle stored proc with Crystal reports.
Check at:
https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/1084c536-711e-2b10-e48a-924a60745253
It is for older version but it should work and you can refer to it to get general idea how to start with it. It has a sample oracle stored proc and how to connect it from Crystal Reports. -
Hi i am using oracle 10g how to view the content of the stored procedure or trigger ?
Hi i am using oracle 10g .How to edit the content of the stored procedure or trigger ?
jklopkjl wrote:
Hi i am using oracle 10g .How to view the content of the stored procedure or trigger ?
query ALL_SOURCE
SQL> desc all_source
Name Null? Type
OWNER VARCHAR2(30)
NAME VARCHAR2(30)
TYPE VARCHAR2(12)
LINE NUMBER
TEXT VARCHAR2(4000) -
How to call a stored procedure that use a type defined in a package?
Hi all,
this is stored procedure:
GET_GIORNATAEVENTO( in_nome_servizio IN VARCHAR2,
out_dati_aggiornati OUT TAB_VARCHAR2);
TAB VARCHAR2 is defined in the package specification:
TYPE tab_varchar2 IS TABLE OF VARCHAR2(5) INDEX BY BINARY_INTEGER;
and this is the name of the package: PKG_SERVIZI_MMSPUSH.
This is my php script:
<?php
// Connect to database...
$c=OCILogon("venus_vfl", "venus_vfl", "venvi");
if ( ! $c ) {
echo "Connessione non riuscita: " . var_dump( OCIError() );
die();
echo "<br>PKG_SERVIZI_MMSPUSH.GET_GIORNATAEVENTO</br> ";
echo "<br> </br>";
// Call database procedure...
$in_servizio = "MOTO";
$s = OCIParse($c, "begin PKG_SERVIZI_MMSPUSH.GET_GIORNATAEVENTO(:bind1, :bind2); end;");
OCIBindByName($s, ":bind1", $in_servizio);
OCIBindByName($s, ":bind2", $out_esito);
OCIExecute($s,OCI_DEFAULT);
echo "OUT_DATI_AGGIORNATI= " . $out_esito;
// Logoff from Oracle
OCILogoff($c);
?>
How to test stored procedure to get the output parameter?
Thanks in advance.Thanks,
but I need to test stored procedures that uses type defined in the package.
e.g.
if I have s.p.
PROCEDURE get_risultati_squadra
( in_squadra IN VARCHAR2,
out_serie OUT tab_varchar2_5,
out_tiporisultato OUT tab_varchar2_5,
out_n_giornata OUT tab_varchar2_5,
out_squadre OUT tab_varchar2_200,
out_risultato OUT tab_varchar2_10,
out_marcatore OUT tab_varchar2_50,
out_punti OUT tab_varchar2_3,
out_rimbalzista OUT tab_varchar2_50,
out_rimbalzi OUT tab_varchar2_3,
out_esito OUT tab_varchar2_2);
I have to define every type external to the package, in this case five new TYPE !!
Is there another way to solve this problem?
Thanks -
How to return object type from external c procedure ?
Hello all,
I'm trying for the first time to return an object type as the return value of an external stored procedure (in C ).
I don't have any issue to use an object type parameter for the function but not to return one to the caller.
each time I try I get "ORA-03113: end-of-file on communication channel" and the connection is dropped.
Thanks for any help,
Roye Avidor
here is the code :
=> object type
SQL>create or replace type address as object ( age number, salary float );
=> address typ file
CASE=SAME
TYPE address as address
=> building the dependences structures.
$>ott userid=scott/tiger intype=address.type code=c hfile=address.h
=> the package description
create or replace package userTypeDefined_PKG
is
function getAddr( addr address ) return address;
end;
create or replace package body userTypeDefined_PKG
is
function getAddr( addr address ) return address
AS LANGUAGE C
NAME "addr"
LIBRARY userTypeDefinedLib
WITH CONTEXT
PARAMETERS
( CONTEXT,
addr,
addr INDICATOR STRUCT ,
return address,
return INDICATOR STRUCT
end;
=> The C code for the library in
address* addr(OCIExtProcContext ctx, address address_obj, address_ind address_obj_ind, address_ind ret_ind){
unsigned int tt;
OCIEnv *envh;
OCIError *errh;
OCISvcCtx *svch;
sword err;
address* ret = NULL;
int inum = 69;
float fnum = 12.34;
/* get OCI Environment */
err = OCIExtProcGetEnv(ctx, &envh, &svch, &errh) ;
/* allocate space for return sturcture*/
ret = (address *)OCIExtProcAllocCallMemory(ctx, sizeof(address));
/* set the AGE value */
if ( OCINumberFromInt ( errh, &inum, sizeof(inum), OCI_NUMBER_SIGNED, &(ret->AGE) ) == OCI_ERROR )
OCIExtProcRaiseExcp(ctx,(int)1476); // raise 1476 is fail
/* set the SALARY value */
if ( OCINumberFromReal ( errh, &fnum, sizeof(fnum), &(ret->SALARY) ) == OCI_ERROR )
OCIExtProcRaiseExcp(ctx,(int)1477);// raise 1477 is fail
// set the indicators for the structure as not null
ret_ind->atomic = OCIIND_NOTNULL;
ret_ind->AGE = OCI_IND_NOTNULL;
ret_ind->SALARY = OCI_IND_NOTNULL;
return (ret);
}The return indicator should be declared as double pointer, and need to be allocated in the function body.
-
How to pass an array to a stored procedure
create or replace package demo_pkg
as
type cityArray is table of city%rowtype index by binary_integer;
procedure city_report( p_inputs in cityArray );
end;
CREATE OR REPLACE PACKAGE BODY demo_pkg
AS
PROCEDURE city_report (p_inputs IN cityarray)
IS
BEGIN
FOR i IN 1 .. p_inputs.COUNT
LOOP
DBMS_OUTPUT.put_line ( 'citycode = '
|| p_inputs (i).city_code
|| ' CITYDESCRIPTION = '
|| p_inputs (i).city_description
INSERT INTO testing
(city_code, city_description
VALUES (p_inputs (i).city_code, p_inputs (i).city_description
commit;
END LOOP;
END;
END;
to call that procedure ia m using this
declare
my_data demo_pkg.cityArray;
begin
my_data(1).city_code := 1234;
my_data(1).CITY_DESCRIPTION := 10;
my_data(2).city_code := 4567;
my_data(2).CITY_DESCRIPTION := 20;
my_data(3).city_code := 4321;
my_data(3).CITY_DESCRIPTION := 30;
demo_pkg.city_report( my_data );
end;
but actually the procedure (demo_pkg.city_report)is called from front end(.net).how they will call this procedure in .net invironmentHi,
Your exact question has been asked before, see: http://asktom.oracle.com/pls/ask/search?p_string=How+to+pass+an+array+to+a+stored+procedure
or do a search on this forum.
And please use this tag => (yes, just the 4 characters forming the word 'code' between curly brackets)
*before* and *after* your example to maintain formatting and indentation, it's hard to read now....
Maybe you are looking for
-
I downloaded CS6 Red Plug-In and added to Package Contents, replaced the current files with the new without backing up, now my RED footage thumbnails and color-correction don't WORK! How do I get my old importerRed file back!!?? HELP!
-
Error editing data file, unable to load Region Definition
Hello I'm getting a parseException when I try to edit a data file from UCM. The steps followed are: 1- Create an element definition at Site Studio 2 - Create a Region Definition refering to the Element Definition 3 - Create a Content i
-
Remote Debugging w/Eclipse Transport Error
I am requesting help on a problem I am encountering using remote debugging with eclipse and Weblogic 8.1.2. I have successfully used remote debugging in the past with other application servers, but I have been unsuccessful with Weblogic 8.1. I have s
-
Flashback buf free by RVWR is in top-5 wait event.
Hi Team, I am having slowness in my database. due to this i am getting some of the query getting timed out. while i view the AWR ,i am seeing the wait event-flashback buf free by RVWR. Can you please help me will it affect the database performance. a
-
Can PIVOT be used in this version 'Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi'. And how to identify whether some functions are available in my version or not. I am using TOAD 9.7.2.5.