SQR - Ref Cursor
<p>I am trying to call an Oracle stored procedure within SQR thatreturns a ref cursor. I am able to successfully do this onlyif I run the program as the schema owner. I read that SQRneeds to be able to do a describe on the stored procedure in orderfor the program to work. I can do a describe but only if Iinclude the schema owner (ex. schema_owner.stored_procedure). So, logically, I tried to add the schema owner to the storedprocedure name within sqr. When I do this I get the error(SQR 3918) Missing Stored Procedure or Function.</p><p> </p><p>Here is the syntax below:</p><p>execute on-error=ora_err do=print_plan_type<br> @#retVal=HRIS.HRIS_HRS_DS_PACKAGE.Get_Plan_Type_List@rc01=$planCursor OUT<br> INTO &pc_ext_app_id varchar2(3)</p><p> </p><p>Any thoughts on how I can get SQR to recognize the schemaowner?<br></p>
Here's a link:
PL/SQL Users Guide and Reference
cheers,
Anthony
Similar Messages
-
Odd error while opening a ref cursor
Hi.
I have a procedure in a package that has both in and out parameters. One of those out parameters is a ref cursor. The procedure creates a dynamic query and then executes it, then it opens the cursor:
PROCEDURE PROC(
A IN VARCHAR2,
B IN VARCHAR2,
C OUT TYPES.cursorType; --(TYPES is a package whose only use is to declare a cursor type)
) IS
--DECLARATIONS
OPEN C FOR 'SELECT A, B, C, D...';
END;
When I execute the package in an anonymous block it throws the error:
ORA-00938: not enough arguments for function, just in the line where the cursor is being opened.
Any ideas?is everything defined correctly?
create or replace package types as
type cursorType is ref cursor;
end types;
SQL> set serveroutput on
SQL> declare
2
3 ref_C types.cursorType;
4
5 v_a varchar2(1);
6 v_b varchar2(1);
7 v_c varchar2(1);
8 v_d varchar2(1);
9
10 procedure Proc (a in varchar2
11 ,b in varchar2
12 ,C out types.cursorType) as
13
14 begin
15 open C for 'select :1, :2, ''c'', ''d'' from dual' using a, b;
16 end Proc;
17 begin
18
19
20 Proc('a', 'b', ref_C);
21
22 fetch ref_C into v_a, v_b, v_c, v_d;
23 if (ref_C%found) then
24 dbms_output.put_line(v_a);
25 dbms_output.put_line(v_b);
26 dbms_output.put_line(v_c);
27 dbms_output.put_line(v_d);
28 end if;
29
30
31 end;
32 /
a
b
c
dP;
Edited by: bluefrog on Feb 18, 2010 6:07 PM -
The query below will return values in the form of
bu seq eligible
22 2345 Y
22 2345 N
22 1288 N
22 1458 Y
22 1458 N
22 1234 Y
22 1333 N
What I am trying to accomplish is to loop through the records returned.
for each seq if there is a 'N' in the eligible column return no record for that seq
eg seq 2345 has 'Y' and 'N' thus no record should be returned.
seq 1234 has only a 'Y' then return the record
seq 1333 has 'N' so return no record.
How would I accomplish this with a ref Cursor and pass the values to the front end application.
Procedure InvalidNOs(io_CURSOR OUT T_CURSOR)
IS
v_CURSOR T_CURSOR;
BEGIN
OPEN v_CURSOR FOR
' select bu, seq, eligible ' ||
' from (select bu, seq, po, tunit, tdollar,eligible,max(eligible) over () re ' ||
' from (select bu, seq, po, tunit, tdollar,eligible ' ||
' from ( ' ||
' select bu, seq, po, tunit, tdollar, eligible, sum(qty) qty, sum(price*qty) dollars ' ||
' from ' ||
' ( select /*+ use_nl(t,h,d,s) */ ' ||
' h.business_unit_id bu, h.edi_sequence_id seq, d.edi_det_sequ_id dseq, ' ||
' s.edi_size_sequ_id sseq, h.po_number po, h.total_unit tUnit, h.total_amount tDollar, ' ||
' s.quantity qty, s.unit_price price,' ||
' (select (case when count(*) = 0 then ''Y'' else ''N'' end) ' ||
' from sewn.NT_edii_po_det_error ' ||
' where edi_det_sequ_id = d.edi_det_sequ_id ' ||
' ) eligible ' ||
' from sewn.nt_edii_purchase_size s, sewn.nt_edii_purchase_det d, ' ||
' sewn.nt_edii_purchase_hdr h, sewn.nt_edii_param_temp t ' ||
' where h.business_unit_id = t.business_unit_id ' ||
' and h.edi_sequence_id = t.edi_sequence_id ' ||
' and h.business_unit_id = d.business_unit_id ' ||
' and h.edi_sequence_id = d.edi_sequence_id ' ||
' and d.business_unit_id = s.business_unit_id ' ||
' and d.edi_sequence_id = s.edi_sequence_id ' ||
' and d.edi_det_sequ_id = s.edi_det_sequ_id ' ||
' ) group by bu, seq, po, tunit, tdollar, eligible ' ||
' ) ' ||
' group by bu, seq, po, tunit, tdollar, eligible)) ';
io_CURSOR := v_CURSOR;
END InvalidNOs;One remark why you should not use the assignment between ref cursor
variables.
(I remembered I saw already such thing in your code).
Technically you can do it but it does not make sense and it can confuse your results.
In the opposite to usual variables, when your assignment copies value
from one variable to another, cursor variables are pointers to the memory.
Because of this when you assign one cursor variable to another you just
duplicate memory pointers. You don't copy result sets. What you do for
one pointer is that you do for another and vice versa. They are the same.
I think the below example is self-explained:
SQL> /* usual variables */
SQL> declare
2 a number;
3 b number;
4 begin
5 a := 1;
6 b := a;
7 a := a + 1;
8 dbms_output.put_line('a = ' || a);
9 dbms_output.put_line('b = ' || b);
10 end;
11 /
a = 2
b = 1
PL/SQL procedure successfully completed.
SQL> /* cursor variables */
SQL> declare
2 a sys_refcursor;
3 b sys_refcursor;
4 begin
5 open a for select empno from emp;
6 b := a;
7 close b;
8
9 /* next action is impossible - cursor already closed */
10 /* a and b are the same ! */
11 close a;
12 end;
13 /
declare
ERROR at line 1:
ORA-01001: invalid cursor
ORA-06512: at line 11
SQL> declare
2 a sys_refcursor;
3 b sys_refcursor;
4 vempno emp.empno%type;
5
6 begin
7 open a for select empno from emp;
8 b := a;
9
10 /* Fetch first row from a */
11 fetch a into vempno;
12 dbms_output.put_line(vempno);
13
14 /* Fetch from b gives us SECOND row, not first -
15 a and b are the SAME */
16
17 fetch b into vempno;
18 dbms_output.put_line(vempno);
19
20
21 end;
22 /
7369
7499
PL/SQL procedure successfully completed.Rgds.
Message was edited by:
dnikiforov -
Dynamic sql and ref cursors URGENT!!
Hi,
I'm using a long to build a dynamic sql statement. This is limited by about 32k. This is too short for my statement.
The query results in a ref cursor.
Does anyone have an idea to create larger statement or to couple ref cursors, so I can execute the statement a couple of times and as an result I still have one ref cursor.
Example:
/* Determine if project is main project, then select all subprojects */
for i in isMainProject loop
if i.belongstoprojectno is null then
for i in ProjectSubNumbers loop
if ProjectSubNumbers%rowcount=1 then
SqlStatement := InitialStatement || i.projectno;
else
SqlStatement := SqlStatement || PartialStatement || i.projectno;
end if;
end loop;
else
for i in ProjectNumber loop
if ProjectNumber%rowcount=1 then
SqlStatement := InitialStatement || i.projectno;
else
SqlStatement := SqlStatement || PartialStatement || i.projectno;
end if;
end loop;
end if;
end loop;
/* Open ref cursor */
open sql_output for SqlStatement;
Thanks in advance,
Jeroen Muis
KCI Datasystems BV
mailto:[email protected]Example for 'dynamic' ref cursor - dynamic WHERE
(note that Reports need 'static' ref cursor type
for building Report Layout):
1. Stored package
CREATE OR REPLACE PACKAGE report_dynamic IS
TYPE type_ref_cur_sta IS REF CURSOR RETURN dept%ROWTYPE; -- for Report Layout only
TYPE type_ref_cur_dyn IS REF CURSOR;
FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn;
END;
CREATE OR REPLACE PACKAGE BODY report_dynamic IS
FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn IS
ref_cur_dyn type_ref_cur_dyn;
BEGIN
OPEN ref_cur_dyn FOR
'SELECT * FROM dept WHERE ' | | NVL (p_where, '1 = 1');
RETURN ref_cur_dyn;
END;
END;
2. Query PL/SQL in Reports
function QR_1RefCurQuery return report_dynamic.type_ref_cur_sta is
begin
return report_dynamic.func_dyn (:p_where);
end;
Regards
Zlatko Sirotic
null -
ORA-01008 with ref cursor and dynamic sql
When I run the follwing procedure:
variable x refcursor
set autoprint on
begin
Crosstab.pivot(p_max_cols => 4,
p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by job order by deptno) rn from scott.emp group by job, deptno',
p_anchor => Crosstab.array('JOB'),
p_pivot => Crosstab.array('DEPTNO', 'CNT'),
p_cursor => :x );
end;I get the following error:
^----------------
Statement Ignored
set autoprint on
begin
adsmgr.Crosstab.pivot(p_max_cols => 4,
p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by
p_anchor => adsmgr.Crosstab.array('JOB'),
p_pivot => adsmgr.Crosstab.array('DEPTNO', 'CNT'),
p_cursor => :x );
end;
ORA-01008: not all variables bound
I am running this on a stored procedure as follows:
create or replace package Crosstab
as
type refcursor is ref cursor;
type array is table of varchar2(30);
procedure pivot( p_max_cols in number default null,
p_max_cols_query in varchar2 default null,
p_query in varchar2,
p_anchor in array,
p_pivot in array,
p_cursor in out refcursor );
end;
create or replace package body Crosstab
as
procedure pivot( p_max_cols in number default null,
p_max_cols_query in varchar2 default null,
p_query in varchar2,
p_anchor in array,
p_pivot in array,
p_cursor in out refcursor )
as
l_max_cols number;
l_query long;
l_cnames array;
begin
-- figure out the number of columns we must support
-- we either KNOW this or we have a query that can tell us
if ( p_max_cols is not null )
then
l_max_cols := p_max_cols;
elsif ( p_max_cols_query is not null )
then
execute immediate p_max_cols_query into l_max_cols;
else
RAISE_APPLICATION_ERROR(-20001, 'Cannot figure out max cols');
end if;
-- Now, construct the query that can answer the question for us...
-- start with the C1, C2, ... CX columns:
l_query := 'select ';
for i in 1 .. p_anchor.count
loop
l_query := l_query || p_anchor(i) || ',';
end loop;
-- Now add in the C{x+1}... CN columns to be pivoted:
-- the format is "max(decode(rn,1,C{X+1},null)) cx+1_1"
for i in 1 .. l_max_cols
loop
for j in 1 .. p_pivot.count
loop
l_query := l_query ||
'max(decode(rn,'||i||','||
p_pivot(j)||',null)) ' ||
p_pivot(j) || '_' || i || ',';
end loop;
end loop;
-- Now just add in the original query
l_query := rtrim(l_query,',')||' from ( '||p_query||') group by ';
-- and then the group by columns...
for i in 1 .. p_anchor.count
loop
l_query := l_query || p_anchor(i) || ',';
end loop;
l_query := rtrim(l_query,',');
-- and return it
execute immediate 'alter session set cursor_sharing=force';
open p_cursor for l_query;
execute immediate 'alter session set cursor_sharing=exact';
end;
end;
/I can see from the error message that it is ignoring the x declaration, I assume it is because it does not recognise the type refcursor from the procedure.
How do I get it to recognise this?
Thank you in advanceThank you for your help
This is the version of Oracle I am running, so this may have something to do with that.
Oracle9i Enterprise Edition Release 9.2.0.8.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.8.0 - Production
I found this on Ask Tom (http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3027089372477)
Hello, Tom.
I have one bind variable in a dynamic SQL expression.
When I open cursor for this sql, it gets me to ora-01008.
Please consider:
Connected to:
Oracle8i Enterprise Edition Release 8.1.7.4.1 - Production
JServer Release 8.1.7.4.1 - Production
SQL> declare
2 type cur is ref cursor;
3 res cur;
4 begin
5 open res for
6 'select * from (select * from dual where :p = 1) connect by 1 = 1'
7 using 1;
8 end;
9 /
declare
ERROR at line 1:
ORA-01008: not all variables bound
ORA-06512: at line 5
SQL> declare
2 type cur is ref cursor;
3 res cur;
4 begin
5 open res for
6 'select * from (select * from dual where :p = 1) connect by 1 = 1'
7 using 1, 2;
8 end;
9 /
PL/SQL procedure successfully completed.
And if I run the same thing on 10g -- all goes conversely. The first part runs ok, and the second
part reports "ORA-01006: bind variable does not exist" (as it should be, I think). Remember, there
is ONE bind variable in sql, not two. Is it a bug in 8i?
What should we do to avoid this error running the same plsql program code on different Oracle
versions?
P.S. Thank you for your invaluable work on this site.
Followup June 9, 2005 - 6pm US/Eastern:
what is the purpose of this query really?
but it would appear to be a bug in 8i (since it should need but one). You will have to work that
via support. I changed the type to tarray to see if the reserved word was causing a problem.
variable v_refcursor refcursor;
set autoprint on;
begin
crosstab.pivot (p_max_cols => 4,
p_query =>
'SELECT job, COUNT (*) cnt, deptno, ' ||
' ROW_NUMBER () OVER ( ' ||
' PARTITION BY job ' ||
' ORDER BY deptno) rn ' ||
'FROM emp ' ||
'GROUP BY job, deptno',
p_anchor => crosstab.tarray ('JOB'),
p_pivot => crosstab.tarray ('DEPTNO', 'CNT'),
p_cursor => :v_refcursor);
end;
/Was going to use this package as a stored procedure in forms but I not sure it's going to work now. -
Ref cursors and dynamic sql..
I want to be able to use a fuction that will dynamically create a SQL statement and then open a cursor based on that SQL statement and return a ref to that cursor. To achieve that, I am trying to build the sql statement in a varchar2 variable and using that variable to open the ref cursor as in,
open l_stmt for refcurType;
where refcurType is a strong ref cursor. I am unable to do so because I get an error indication that I can not use strong ref cursor type. But, if I can not use a strong ref cursor, I will not be able to use it to build the report based on the ref cursor because Reports 9i requires strong ref cursors to be used. Does that mean I can not use dynamic sql with Reports 9i ref cursors? Else, how I can do that? Any documentation available?Philipp,
Thank you for your reply. My requirement is that, sometimes I need to construct a whole query based on some input, and sometimes not. But the output record set would be same and the layout would be more or less same. I thought ref cursor would be ideal. Ofcourse, I could do this without dynamic SQL by writing the SQL multiple times if needed. But, I think dynamic SQL is a proper candidate for this case. Your suggestion to use lexical variable is indeed a good alternative. In effect, if needed, I could generate an entire SQL statement and place in some place holder (like &stmt) and use it as a static SQL query in my data model. In that case, why would one ever need ref cursor in reports? Is one more efficient over the other? My guess is, in the lexical variable case, part of the processing (like parsing) is done on the app server while in a function based ref cursor, the entire process takes place in the DB server and there is probably a better chance for re-use(?)
Thanks,
Murali. -
Hi..
I'm using a ref cursor query to fetch data for a report and works just fine. However i need to use dynamic sql in the query because the columns used in the where condition and for some calculations may change dynamically according to user input from the form that launches the report..
Ideally the query should look like this:
select
a,b,c
from table
where :x = something
and :y = something
and (abs(:x/:y........)
The user should be able to switch between :x and :y
Is there a way to embed dynamic sql in a ref cursor query in Reports 6i?
Reports 6i
Forms 6i
Windows 2000 PROHello Nicola,
You can parameterize your ref cursor by putting the query's select statement in a procedure/function (defined in your report, or in the database), and populating it based on arguments accepted by the procedure.
For example, the following procedure accepts a strongly typed ref cursor and populates it with emp table data based on the value of the 'mydept' input parameter:
Procedure emp_refcursor(emp_data IN OUT emp_rc, mydept number) as
Begin
-- Open emp_data for select all columns from emp where deptno = mydept;
Open emp_data for select * from emp where deptno = mydept;
End;
This procedure/function can then be called from the ref cursor query program unit defined in your report's data model, to return the filled ref cursor to Reports.
Thanks,
The Oracle Reports Team. -
Ref Cursor over Implicit and explicit cursors
Hi,
In my company when writing PL/SQL procedure, everyone uses "Ref Cursor",
But the article below, says Implicit is best , then Explicit and finally Ref Cursor..
[http://www.oracle-base.com/forums/viewtopic.php?f=2&t=10720]
I am bit confused by this, can any one help me to understand this?
ThanksSeshuGiri wrote:
In my company when writing PL/SQL procedure, everyone uses "Ref Cursor",
But the article below, says Implicit is best , then Explicit and finally Ref Cursor..
[http://www.oracle-base.com/forums/viewtopic.php?f=2&t=10720]
I am bit confused by this, can any one help me to understand this?There is performance and there is performance...
To explain. There is only a single type of cursor in Oracle - that is the cursor that is parsed and compiled by the SQL engine and stored in the database's shared pool. The "+client+" is then given a handle (called a SQL Statement Handle in many APIs) that it can use to reference that cursor in the SQL engine.
The performance of this cursor is not determined by the client. It is determined by the execution plan and how much executing that cursor cost ito server resources.
The client can be Java, Visual Basic, .Net - or a PL/SQL program. This client language (a client of SQL), has its own structures in dealing with that cursor handle received from the SQL engine.
It can hide it from the developer all together - so that he/she does not even see that there is a statement handle. This is what implicit cursors are in PL/SQL.
It can allow the developer to manually define the cursor structure - this is what explicit cursors, ref cursors, and DBMS_SQL cursors are in PL/SQL.
Each of these client cursor structures provides the programmer with a different set of features to deal with SQL cursor. Explicit cursor constructs in PL/SQL do not allow for the use of dynamic SQL. Ref cursors and DBMS_SQL cursors do. Ref cursors do not allow the programmer to determine, at run-time, the structure of the SQL projection of the cursor. DBMS_SQL cursors do.
Only ref cursors can be created in PL/SQL and then be handed over to another client (e.g. Java/VB) for processing. Etc.
So each of the client structures/interfaces provides you with a different feature set for SQL cursors.
Choosing implicit cursors for example does not make the SQL cursor go faster. The SQL engine does not know and does not care, what client construct you are using to deal with the SQL cursor handle it gave you. It does not matter. It does not impact its SQL cursor performance.
But on the client side, it can matter - as your code in dealing with that SQL cursor determines how fast your interaction with that SQL cursor is. How many context switches you make. How effectively you use and re-use the SQL (e.g. hard parsing vs soft parsing vs re-using the same cursor handle). Etc.
Is there any single client cursor construct that is better? No.
That is an ignorant view. The client language provides a toolbox, where each tool has a specific application. The knowledgeable developer will use the right tool for the job. The idiot developer will select one tool and use it as The Hammer to "solve" all the problems. -
Hi,
Does anybody know when/if SQL Developer unit tests will support procedures that return reference cursors?
Thanks
LeeSupport for REF CURSOR is already being considered for a future release although support will probably be under some size constraints as a REF CURSOR can obviously return a massive quantity of data in a production system which is beyond the brief of Unit Testing.
-
MS Access, ODBC and SPs returning ref cursor
I have some functions and procedures in a package returning ref cursors that work fine in my C++ batch applications. I would like for the GUI to be able to call these as well.
Unfortunately, we are using Access as the front end (for now), and we have not been able to get the ref cursors to work. Is this supported? We are using Oracle 8.0.5 on Solaris, and our clients is Access 97 on NT using Intersolv's ODBC driver.
My procedure looks something like:
package jec is
procedure open_sale_cur(
p_client_id number,
sale_curvar out sale_curtype)
is begin
open sale_curtype for select ... ;
end;
end;
And the Access code looks like this:
strSql = "begin jec.open_sale_cur(27, ?); end;"
qdfTemp = conMain.CreateQueryDef("", strSql)
qdfTemp.Parameters(0).Direction = dbParamOutput
qdfTemp.Execute()
This is the error when Execute() is called:
PLS-00306: wrong number or types of arguments in call to 'OPEN_SALE_CUR'
I am not an Access programmer; I am simply passing along this information. Any help would be greatly appreciated.We tried the {call...} syntax originally, but when we use it, we get an Oracle syntax error for the statement
SELECT * FROM {call ...}
Apparently Access prepends "SELECT..." before passing the SQL text to Oracle.
This is also the case for procedures with normal scalars, such as numbers, returned as OUT values. When we use anon PL/SQL syntax and "?" placeholders with such procedures, they work. When we use {call ...} syntax or omit OUT placeholders, they do not.
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Justin Cave ([email protected]):
I suspect that you want to simply execute the statement
strSql = {call open_sale_cur( 27 )}
The ODBC driver will automatically figure out that there's an output parameter which is a ref cursor and return that as the result set. Note that you may want to download the latest 8.0.5 ODBC driver (8.0.5.10 I believe) if there are any problems.
Justin<HR></BLOCKQUOTE>
null -
How to get values from a ref cursor in a procedure
I have a procedure that returns a cursor type of values, but I cannot get the values.
I got error when on how to define the output cursor. Could someone please look at the code and tell me how to correct it?
Thanks in advance.
******************************8
--This is the package
CREATE OR REPLACE PACKAGE Test_SECURITY2 as
type T_RoleTest is ref cursor;
Procedure P_GetUserRole(userID in number, p_cur out T_RoleTest);
end;
CREATE OR REPLACE PACKAGE BODY Test_SECURITY2 as
Procedure P_GetUserRole(userID in number, p_cur out T_RoleTest) as
begin
open p_cur for
select PREO_Role.ROLE_ID,PREO_Role.ROLE_NAME
from preorder.PREO_Role, preorder.PREO_User_Role
where PREO_Role.Role_id = PREO_User_Role.Role_id
and PREO_User_Role.user_id = userid;
end;
end;
--This is the testing code. I got error here
SQL> set serveroutput on;
SQL> execute dbms_output.enable;
PL/SQL procedure successfully completed.
SQL> declare
2 type T_RoleTest is ref cursor;
3 V_UserRole is ref cursor; --how to define the output cursor
4 v_userId number := 42;
5 V_Role_Id number;
6 v_Role_name varchar2(20);
7 begin
8 Test_SECURITY2.P_GetUserRole(v_userId, V_UserRole);
9
10 open V_UserRole;
11 loop
12 fetch V_UserRole into V_Role_Id, v_Role_name;
13
14 EXIT WHEN V_UserRole%NOTFOUND;
15 dbms_output.put_line('RoleID'||v_Role_ID);
16 dbms_output.put_line('Rolename'||v_Role_name);
17
18 end loop;
19
20 end;
21 /
V_UserRole is ref cursor;
ERROR at line 3:
ORA-06550: line 3, column 13:
PLS-00103: Encountered the symbol "IS" when expecting one of the following:
constant exception <an identifier>declare
type T_RoleTest is ref cursor;
v_UserRole T_RoleTest;or just:
declare
v_UserRole Test_Security2.T_RoleTest;And, if you are on 9i or later, you can just use the built-in sys_refcursor type. -
Performance problem with sproc and out parameter ref cursor
Hi
I have sproc with Ref Cursor as an OUT parameter.
It is extremely slow looping over the ResultSet (does it record by record in the fetch).
so I have added setPrefetchRowCount(100) and setPrefetchMemorySize(6000)
pseudo code below:
string sqlSmt = "BEGIN get_tick_data( :v1 , :v2); END;";
Statement* s = connection->createStatement(sqlStmt);
s->setString(1, i1);
// cursor ( f1 , f2, f3 , f4 , i1 ) f for float type and i for interger value.
// 5 columns as part of cursor with 4 columns are having float value and
// 1 column is having int value assuming 40 bytes for one rec.
s->setPrefetchRowCount (100);
s->PrefetchMemorySize(6000);
s->registerOutParam(2,OCCICURSOR);
s->execute();
ResultSet* rs = s->getCursor(2);
while (rs->next()) {
// do, and do v slowly!
}Hi,
I have the same problem. It seems, when retrieving cursor, that "setPrefetchRowCount" is not taking into account by OCCI. If you have a SQL statement like "SELECT STR1, STR2, STR3 FROM TABLE1" that works fine but if your SQL statement is a call to a stored procedure returning a cursor each row fetching need a roudtrip.
To avoid this problem you need to use the method "setDataBuffer" from the object "ResultSet" for each column of your cursor. It's easy to use with INT type and STRING type, a lit bit more complex with DATE type. But until now, I'm not able to do the same thing with REF type.
Below a sample with STRING TYPE (It's assuming that the cursor return only one column of STRING type):
try
l_Statement = m_Connection->createStatement("BEGIN :1 := PACKAGE1.GetCursor1(:2); END;");
l_Statement->registerOutParam(1, oracle::occi::OCCINUMBER, sizeof(l_CodeErreur));
l_Statement->registerOutParam(2, oracle::occi::OCCICURSOR);
l_Statement->executeQuery();
l_CodeErreur = l_Statement->getNumber(1);
if ((int) l_CodeErreur == 0)
char l_ArrayName[5][256];
ub2 l_ArrayNameSize[5];
l_ResultSet = l_Statement->getCursor(2);
l_ResultSet->setDataBuffer(1, l_ArrayName, OCCI_SQLT_STR, sizeof(l_ArrayName[0]), l_ArrayNameSize, NULL, NULL);
while (l_ResultSet->next(5))
for (int i = 0; i < l_ResultSet->getNumArrayRows(); i++)
l_Name = CString(l_ArrayName);
l_Statement->closeResultSet(l_ResultSet);
m_Connection->terminateStatement(l_Statement);
catch (SQLException &p_SQLException)
I hope that sample help you.
Regards -
How to give ref cursor in VB procedure call
This is my Oracle Sp
CREATE OR REPLACE PROCEDURE CRD_DMAN.infy_usp_trades_by_broker_bkr
** Procedure name: CRD_DMAN.USP_TRADES_BY_BROKER
** Author's name: Infosys
** Date written: 04/11/07
** Description: Compliance Trade by Borker
** Maintenance history:
** Date Chg req# Name Remarks
** 04/11/07 Infosys Created
p_ordercursor IN OUT infy_pkg_compliance_transact.cur_compliancetrade,
p_startdate IN VARCHAR,
p_enddate IN VARCHAR,
p_fundcode IN cs_fund_config.parent_acct_cd%TYPE,
p_clientcode IN ts_order_alloc.acct_cd%TYPE,
p_brokercode IN ts_order_alloc.exec_broker%TYPE,
p_reportname IN report_log.report_name%TYPE,
p_callingapplication IN report_log.calling_application%TYPE,
p_callinguser IN report_log.calling_user%TYPE
IS
--Declaring Local Variables
v_owner VARCHAR2 (30);
v_startdate VARCHAR2 (10);
v_enddate VARCHAR2 (10);
v_rowcount NUMBER:=0;
v_logrec base_util_pkg.crd_log_record;
exp_error EXCEPTION;
v_fundcodevalue NUMBER;
BEGIN
BEGIN
/*checking if the start date and end date are null and
assigning the sysdate accordingly*/
IF (TRIM(p_startdate) IS NULL )
THEN
v_startdate := TO_CHAR (SYSDATE, 'mm/dd/yy');
ELSE
v_startdate := p_startdate;
END IF;
IF (TRIM(p_enddate) IS NULL )
THEN
v_enddate := TO_CHAR (SYSDATE, 'mm/dd/yy');
ELSE
v_enddate := p_enddate;
END IF;
/*checking if fund code is null and assigning value accordingly*/
IF TRIM (p_fundcode) IS NULL
THEN
v_fundcodevalue := 0;
ELSE
v_fundcodevalue := 1;
END IF;
/*checking if the reportname or calling user or calling
application name*/
IF (p_reportname IS NULL OR p_callinguser IS NULL
OR p_callingapplication IS NULL)
THEN
RAISE exp_error;
END IF;
END;
--opening and fetching the data into cursor
v_logrec.start_time := SYSDATE;
BEGIN
OPEN p_ordercursor
FOR
SELECT
oa.exec_broker EXEC_BROKER_CODE,
b.bkr_name EXEC_BROKER_NAME,
oa.acct_cd CLIENT_CODE,
f.acct_name CLIENT_NAME,
CASE WHEN (Exists (SELECT 1
FROM cs_fund_broker fb
WHERE rel_typ_cd IN('P','M')
AND oa.exec_broker=fb.BKR_CD
AND oa.acct_cd =fb.acct_cd))
THEN 'Y'
ELSE 'N' END DIRECTED_BROKER,
COUNT ( distinct o.order_id) COUNT_TICKNUM,
MAX (o.trade_date) TRADE_DATE,
SUM (oa.exec_amt) BASE_COST,
SUM (oa.commision_amt) TOTAL_COMMISSION,
(SELECT ab.bkr_typ_cd FROM au_broker ab
WHERE ab.au_change_date =(SELECT TO_TIMESTAMP(MAX(ab.au_change_date))
FROM au_broker ab WHERE b.bkr_typ_cd != ab.bkr_typ_cd AND b.bkr_cd = ab.bkr_cd))
BROKER_HISTORY
FROM
ts_order o
JOIN ts_order_alloc oa ON (o.order_id = oa.order_id)
JOIN cs_broker b ON(oa.exec_broker = b.bkr_cd)
JOIN cs_fund f ON(oa.acct_cd = f.acct_cd)
WHERE
o.status = 'ACCT'
AND oa.exec_broker = CASE WHEN TRIM (p_brokercode) IS NULL
THEN oa.exec_broker
ELSE TRIM(p_brokercode) END
AND oa.acct_cd = CASE WHEN TRIM(p_clientcode) IS NULL
THEN oa.acct_cd
ELSE TRIM(p_clientcode) END
AND ((0 = v_fundcodevalue) OR EXISTS (SELECT 1 FROM crd.cs_fund_config cf
WHERE cf.parent_acct_cd =TRIM (p_fundcode)
AND oa.acct_cd = cf.child_acct_cd))
AND o.trade_date BETWEEN TO_DATE (v_startdate, 'mm/dd/yy')
AND TO_DATE (v_enddate, 'mm/dd/yy')
GROUP BY oa.exec_broker, b.bkr_name ,oa.acct_cd ,f.acct_name,oa.directed_broker,b.bkr_typ_cd,b.bkr_cd;
END;
BEGIN
SELECT
owner
INTO
v_owner
FROM
all_objects
WHERE
object_name = 'INFY_USP_TRADES_BY_BROKER_BKR';
v_logrec.end_time := SYSDATE;
v_logrec.user_code := v_owner;
v_logrec.input_param_values := 'INFY_USP_TRADES_BY_BROKER_BKR,'
|| v_startdate
|| ','
|| v_enddate
|| ','
|| p_fundcode
|| ','
|| p_clientcode
|| ','
|| p_brokercode;
v_logrec.report_name := p_reportname;
v_logrec.object_name := 'INFY_USP_TRADES_BY_BROKER_BKR';
v_logrec.rows_returned := v_rowcount;
v_logrec.calling_application := p_callingapplication;
v_logrec.calling_user := p_callinguser;
END;
BEGIN
--calling the procedure to insert values into the report_log table
COMMIT;
SET TRANSACTION READ WRITE;
base_util_pkg.crd_base_util_proc (v_logrec);
SET TRANSACTION READ ONLY;
END;
EXCEPTION
WHEN exp_error
THEN
DBMS_OUTPUT.put_line ('ERROR');
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ('ERROR OCCURED' || SQLCODE);
DBMS_OUTPUT.put_line (SQLERRM);
END infy_usp_trades_by_broker_bkr;
END OF CRD_DMAN.USP_TRADES_BY_BROKER
This is my Pakage from where i am using ref cursor
CREATE OR REPLACE PACKAGE CRD_DMAN.infy_pkg_compliance_transact
AS
** Package name : CRD.INFY_PKG_COMPLIANCE_TRANSACTIONS
** Author's name : Infosys
** Date written : 06/11/07
** Project/System : CRD
** Description : Compliance Trades By Borker Package
** Maintenance history:
** Date Chg req# Name Remarks
** 06/11/07 CRD Infosys Created
--Defining The ComplianceTrade Record DataType
TYPE rec_compliancetrade IS RECORD (
exec_broker_code crd.ts_order_alloc.exec_broker%TYPE,
exec_broker_name crd.cs_broker.bkr_name%TYPE,
client_code crd.ts_order_alloc.acct_cd%TYPE,
client_name crd.cs_fund.acct_name%TYPE,
directed_broker crd.ts_order_alloc.directed_broker%TYPE,
count_ticknum crd.ts_order.order_id%TYPE,
trade_date crd.ts_order.trade_date%TYPE,
base_cost crd.ts_order_alloc.cur_base_mkt_val%TYPE,
total_commission crd.ts_order_alloc.commision_amt%TYPE,
broker_history crd.au_broker.bkr_typ_cd%TYPE
--Declaring a variable of rec_auditdata data type
TYPE cur_compliancetrade IS REF CURSOR
RETURN rec_compliancetrade;
END infy_pkg_compliance_transact;
END OF CRD.INFY_PKG_COMPLIANCE_TRANSACTIONS
How to call this SP from VB code with ref cursor parameter?I'm fairly sure that's not possible, since there's nothing in the ODBC spec to allow for ref cursors. The driver has built in support to check for ref cursors that are returned via a stored procedure call, but there's nothing built into the driver to pass one IN. Since a ref cursor can't be constructed on the client side, you'd have to have some sort of structure that allowed you to reference the ref cursor directly in order to be able to pass one back to the database.
Since you're using VB.NET anyway, the better solution is probably just to use ODP.NET instead, which DOES allow you to reference a ref cursor directly, and there are samples that install with ODP.NET that show you how to do that.
Greg -
Report using ref cursor or dynamic Sql
Hi,
I never create a report using a ref cursor or a dynamic sql. Could any one help me to solve the below issue.
I have 2 tables.
1. Student_Record
2. Student_csv_help
Student_Record the main table where the data is stored.
Student_csv_help will contain the all the column names of the Student_record.
CREATE TABLE Student_CSV_HELP
ENTRY_ID NUMBER,
RAW_NAME VARCHAR2(40 BYTE),
DESC_NAME VARCHAR2(1000 BYTE),
IN_OUTPUT_LIST VARCHAR2(1 BYTE)
SET DEFINE OFF;
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(1, 'S_ID', 'Student ID', 'Y');
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(2, 'S_Name', 'Student Name', 'Y');
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(3, 'S_Join_date', 'Joining Date', 'Y');
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(4, 'S_Address', 'Address', 'Y');
Insert into TOA_CSV_HELP
(ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
Values
(5, 'S_Fee', 'Tution Fee', 'N');
commit;
CREATE TABLE Student_record
S_ID NUMBER,
S_Name VARCHAR2(100 BYTE),
S_Join_date date,
S_Address VARCHAR2(360 BYTE),
S_Fee Number
Insert into Student_record
(S_ID, S_Name, S_Join_date, S_Address,S_Fee)
Values
(101, 'john', TO_DATE('12/17/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94777', 2000);
Insert into Student_record
(S_ID, S_Name, S_Join_date, S_Address,S_Fee)
Values
(102, 'arif', TO_DATE('12/18/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94444', 3000);
Insert into Student_record
(S_ID, S_Name, S_Join_date, S_Address,S_Fee)
Values
(103, 'raj', TO_DATE('12/19/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94555', 2500);
Insert into Student_record
(S_ID, S_Name, S_Join_date, S_Address,S_Fee)
Values
(104, 'singh', TO_DATE('12/20/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94666', 2000);
Commit;
Now my requirement is:
I have a form with Student_record data block. When i Click on print Button on this form. It will open another window which has Student_CSV_HELP.DESC_NAME and a check box before this.
The window look like as below:
check_box DESC_NAME+
X S_ID+
-- S_Name+
X S_Join_date+
X S_Address+
-- S_Fee+
X means check box checked.+
-- means check box Unchecked.+
After i selected these check boxes i will send 2 parameters to the report server
1. a string parameter to the report server which has the value 'S_ID,S_Join_date,S_Address' (p_column_name := 'S_ID,S_Join_date,S_Address');
2. the s_id value from the student_record block (p_S_id := '101');
Now my requirement is when i click on run. I need a report like as below:
Student ID : 101+
Joining Date : 12/17/2009 08:00:00+
Address : CA-94777+
This is nothing but the ref cursor should run like as below:
Select S_id from student_record block S_id = :p_S_id;
Select S_Join_date from student_record block S_id = :p_S_id;
Select S_Address from student_record block S_id = :p_S_id;
So, according to my understanding i have to select the columns at the run time. I dont have much knowledge in creating reports using ref cursor or dynamic sql.
So please help me to solve this issue.
Thanks in advance.Plain sql should satisfy your need. Try ....
Select S_id, S_Join_date, S_Address
from student_record
where S_id = :p_S_id -
How can I iterate over the columns of a REF CURSOR?
I have the following situation:
DECLARE
text VARCHAR2 (100) := '';
TYPE gen_cursor is ref cursor;
c_gen gen_cursor;
CURSOR c_tmp
IS
SELECT *
FROM CROSS_TBL
ORDER BY sn;
BEGIN
FOR tmp IN c_tmp
LOOP
text := 'select * from ' || tmp.table_name || ' where seqnum = ' || tmp.sn;
OPEN c_gen FOR text;
-- here I want to iterate over the columns of c_gen
-- c_gen will have different number of columns every time,
-- because we select from a different table
-- I have more than 500 tables, so I cannot define strong REF CURSOR types!
-- I need something like
l := c_gen.columns.length;
for c in c_gen.columns[1]..c_gen.columns[l]
LOOP
-- do something with the column value
END LOOP;
END LOOP;
END;As you can see from the comments in the code, I couln'd find any examples on the internet with weak REF CURSORS and selecting from many tables.
What I found was:
CREATE PACKAGE admin_data AS
TYPE gencurtyp IS REF CURSOR;
PROCEDURE open_cv (generic_cv IN OUT gencurtyp, choice INT);
END admin_data;
CREATE PACKAGE BODY admin_data AS
PROCEDURE open_cv (generic_cv IN OUT gencurtyp, choice INT) IS
BEGIN
IF choice = 1 THEN
OPEN generic_cv FOR SELECT * FROM employees;
ELSIF choice = 2 THEN
OPEN generic_cv FOR SELECT * FROM departments;
ELSIF choice = 3 THEN
OPEN generic_cv FOR SELECT * FROM jobs;
END IF;
END;
END admin_data;
/But they have only 3 tables here and I have like 500. What can I do here?
Thanks in advance for any help!The issue here is that you don't know your columns at design time (which is generally considered bad design practice anyway).
In 10g or before, you would have to use the DBMS_SQL package to be able to iterate over each of the columns that are parsed from the query... e.g.
CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2) IS
v_v_val VARCHAR2(4000);
v_n_val NUMBER;
v_d_val DATE;
v_ret NUMBER;
c NUMBER;
d NUMBER;
col_cnt INTEGER;
f BOOLEAN;
rec_tab DBMS_SQL.DESC_TAB;
col_num NUMBER;
v_rowcount NUMBER := 0;
BEGIN
-- create a cursor
c := DBMS_SQL.OPEN_CURSOR;
-- parse the SQL statement into the cursor
DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
-- execute the cursor
d := DBMS_SQL.EXECUTE(c);
-- Describe the columns returned by the SQL statement
DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
-- Bind local return variables to the various columns based on their types
FOR j in 1..col_cnt
LOOP
CASE rec_tab(j).col_type
WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); -- Varchar2
WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val); -- Number
WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val); -- Date
ELSE
DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); -- Any other type return as varchar2
END CASE;
END LOOP;
-- Display what columns are being returned...
DBMS_OUTPUT.PUT_LINE('-- Columns --');
FOR j in 1..col_cnt
LOOP
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' - '||case rec_tab(j).col_type when 1 then 'VARCHAR2'
when 2 then 'NUMBER'
when 12 then 'DATE'
else 'Other' end);
END LOOP;
DBMS_OUTPUT.PUT_LINE('-------------');
-- This part outputs the DATA
LOOP
-- Fetch a row of data through the cursor
v_ret := DBMS_SQL.FETCH_ROWS(c);
-- Exit when no more rows
EXIT WHEN v_ret = 0;
v_rowcount := v_rowcount + 1;
DBMS_OUTPUT.PUT_LINE('Row: '||v_rowcount);
DBMS_OUTPUT.PUT_LINE('--------------');
-- Fetch the value of each column from the row
FOR j in 1..col_cnt
LOOP
-- Fetch each column into the correct data type based on the description of the column
CASE rec_tab(j).col_type
WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_n_val);
WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'));
ELSE
DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
END CASE;
END LOOP;
DBMS_OUTPUT.PUT_LINE('--------------');
END LOOP;
-- Close the cursor now we have finished with it
DBMS_SQL.CLOSE_CURSOR(c);
END;
SQL> exec run_query('select empno, ename, deptno, sal from emp where deptno = 10');
-- Columns --
EMPNO - NUMBER
ENAME - VARCHAR2
DEPTNO - NUMBER
SAL - NUMBER
Row: 1
EMPNO : 7782
ENAME : CLARK
DEPTNO : 10
SAL : 2450
Row: 2
EMPNO : 7839
ENAME : KING
DEPTNO : 10
SAL : 5000
Row: 3
EMPNO : 7934
ENAME : MILLER
DEPTNO : 10
SAL : 1300
PL/SQL procedure successfully completed.
SQL> exec run_query('select * from emp where deptno = 10');
-- Columns --
EMPNO - NUMBER
ENAME - VARCHAR2
JOB - VARCHAR2
MGR - NUMBER
HIREDATE - DATE
SAL - NUMBER
COMM - NUMBER
DEPTNO - NUMBER
Row: 1
EMPNO : 7782
ENAME : CLARK
JOB : MANAGER
MGR : 7839
HIREDATE : 09/06/1981 00:00:00
SAL : 2450
COMM :
DEPTNO : 10
Row: 2
EMPNO : 7839
ENAME : KING
JOB : PRESIDENT
MGR :
HIREDATE : 17/11/1981 00:00:00
SAL : 5000
COMM :
DEPTNO : 10
Row: 3
EMPNO : 7934
ENAME : MILLER
JOB : CLERK
MGR : 7782
HIREDATE : 23/01/1982 00:00:00
SAL : 1300
COMM :
DEPTNO : 10
PL/SQL procedure successfully completed.
SQL> exec run_query('select * from dept where deptno = 10');
-- Columns --
DEPTNO - NUMBER
DNAME - VARCHAR2
LOC - VARCHAR2
Row: 1
DEPTNO : 10
DNAME : ACCOUNTING
LOC : NEW YORK
PL/SQL procedure successfully completed.
SQL>From 11g onwards, you can create your query as a REF_CURSOR, but then you would still have to use the DBMS_SQL package with it's new functions to turn the refcursor into a dbms_sql cursor so that you can then describe the columns in the same way.
http://technology.amis.nl/blog/2332/oracle-11g-describing-a-refcursor
Welcome to the issues that are common when you start to attempt to create dynamic code. If your design isn't specific then your code can't be either and you end up creating more work in the coding whilst reducing the work in the design. ;)
Maybe you are looking for
-
How to support multiple users at the same time?
Hi all, I have a Labview software which controls a analyzer via GPIB connector. When user A is using the software, user B has to wait until A is done. But actually, the analyzer is not very busy, when user A is using the software. I want user A, B, C
-
Trying to export to PDF from InDesign CS6 but nothing happens
I'm in InDesign CS6 and when I export to PDF, nothing happens. I have other files with the same format and they are exporting fine. I tried putting all the content into a new document but it still doesn't work. Has anyone else had this issue? Thank y
-
OSX Server Mobile Account Greyed out after initial setup?
I just setup a new install of Mountain Lion on an iMac and installed Server.app to set it up as a server. I activated Open Directory and configured it for a few users (with NFS mounted home directories from a Linux NFS server). I then logged into t
-
Plug-in errors in Illustrator CS5 for Mac
I recently installed the Design Premium version of CS5 on my work computer. Everything was going fine in Illustrator until today, when I tried to add some older brushes, patterns, symbols to the presets folder. Now Illustrator is loading with tons of
-
Update termination record found in SM13 - material document posting error
Hi All, A record was found in SM13 relating to missing material document and accounting document. When 'update header' button is clicked in SM13 selecting that record, the resultant pop up shows report name SAPLZ2K_MB_BUS2028. And when 'update status