Cursor Variables in Pro*C/C++
I have very strange behaivour of the client application that uses cursor variable.
I have Oracle 8i enterprise 8.1.6 release for Sun/Solaris.
The follow SQL is installed on server:
create or replace package dummy is
type vemap_cur is ref cursor;
end;
create or replace procedure GET_CUR
( N IN number, cur IN OUT dummy.VEMAP_CUR ) as
begin
open cur for
select LS.ID, LS.SCALE
from LAYERS LS
where LS.ID = (select C.ID from CTM C where C.ORDERINDEX = N);
end;
This procedure (GET_CUR) i call from embedded SQL in follow manner:
EXEC SQL BEGIN DECLARE SECTION;
struct
int n1;
int n2;
} resrec;
sql_cursor c1;
int num;
EXEC SQL END DECLARE SECTION;
EXEC SQL ALLOCATE :c1;
EXEC SQL AT DB_VE EXECUTE
BEGIN
GET_VEC( :num, :c1 );
END;
END-EXEC;
Till now it is Ok. But when i run the follow line
EXEC SQL FETCH :c1 INTO :resrec;
i accept ORA-01012: not logged on
error !!!!
I checked the connection via using cursor in paralell and got the correct answer.
Therefore i think this error is not related to the actual problem and i have no idea what this problem is. I tried to open cursor via anonymous PL/SQL block inside my C program with same result.
Need help ASAP.
Leonid
null
Hi Leonid, Andrea
When you use "CONNECT AT :db_handle" instead of default connection "CONNECT", you have to give the connect handle to the command you want to execute.
ie:
EXEC SQL AT :db_handle PREPARE SQL_stat FROM "select ...";
EXEC SQL AT :db_handle DECLARE cur_stat CURSOR for SQL_stat;
EXEC SQL AT :db_handle OPEN cur_stat ;
EXEC SQL AT :db_handle FETCH cur_stat INTO :resrec;
Leonid, the error you had is probably because you connected at "DB_VE", and tried to select from default connect (that you're not connected to ==> ORA-01012)
Try EXEC SQL AT :DB_VE FETCH :c1 INTO :resrec;
or, if you connect to only 1 database, use "EXEC SQL CONNECT;" instead of (EXEC SQL CONNECT :pConnectString AT "DB_VE";) so that you use default connect name and you don't have to add "AT :DB_VE" to your SQL commands.
I know this reply comes long after your request, but I hope it may still help anybody.
Similar Messages
-
Dynamic SQL with cursor variables in pro*c
Please, what I need to do in order to be able
to do something like this:
EXEC SQL DECLARE :c CURSOR FOR :s;
In other words: I want to use variables
in cursor names.
Is it possible ? How ?
Thank you.OK. Here is an example of a Dynamic SQL #4 program I wrote several years ago (It's still running in production). It is currently running on a Sun E10K with Oracle 8.1.5. This code is JUST the pro*c part of a program which uses IBM MQ Series. MQ passes this program a Select SQL statement (as well as other parameters) as an argument. The Pro*c code allocates the structures, parses, and fetches, and executes the statement. I realize that this will not be easy to read. There are SOME comments in the code. However, I realize that to read anyone elses code is a chore. When you add Dynamic #4 to the list, it becomes much more complicated. Anyway, you'll probably need to copy and paste the code to a text file. It will be easier to read.
==========================================
Code
==========================================
| Program: mqsql.pc |
| Creator: Jim Wartnick |
| Purpose: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX |
| XXXXXXXXXXX |
| Date: 01/03/1997 |
| Modifications: |
#include"mqsql.h"
#define DEBUG
#ifdef DEBUG
FILE *fp=stdout;
#endif
int
disconnect_db() {
char msg[256], oraclmsg[256];
char buf[MAX_STRING_LENGTH+4];
int buf_len = 0, msg_len = 0;
EXEC SQL
COMMIT WORK RELEASE;
#ifdef DEBUG
fprintf(fp, " --> Disconnecting from database. RC: %d.\n", sqlca.sqlcode);
fflush(fp);
#endif
if (sqlca.sqlcode != 0) {
buf_len = sizeof(oraclmsg)-1;
sqlglm(oraclmsg, &buf_len, &msg_len);
oraclmsg[msg_len] = '\0';
error("disconnect_db()", "disconnect", sqlca.sqlcode, oraclmsg);
return(FAILURE);
return(SUCCESS);
int
connect_db() {
char msg[256], oraclmsg[256];
char buf[MAX_STRING_LENGTH+4];
int buf_len = 0, msg_len = 0;
char user[4];
strcpy(user, "/");
EXEC SQL
CONNECT :user;
#ifdef DEBUG
fprintf(fp, " --> Connecting to database. RC is %d\n", sqlca.sqlcode);
fflush(fp);
#endif
if (sqlca.sqlcode != 0) {
buf_len = sizeof(oraclmsg)-1;
sqlglm(oraclmsg, &buf_len, &msg_len);
oraclmsg[msg_len] = '\0';
sprintf(Results, "%9d", sqlca.sqlcode);
error("connect_db()", "connect", sqlca.sqlcode, oraclmsg);
return(FAILURE);
return(SUCCESS);
int
allocate_sqlda() {
| Initialize the SQLDA structure. |
| We only need the select descriptor |
| because we do not have any bind |
| variables. |
if ((Select_da = sqlald(
MAX_COLUMN_COUNT,
MAX_COLUMN_STRING_LENGTH,
MAX_INDICATOR_VARS
)) == (SQLDA *) 0) {
#ifdef DEBUG
fprintf(fp, " Memory allocation for Select Descriptor failed.\n");
fflush(fp);
#endif
strcpy(Results, "000000001");
error("allocate_sqlda()", "create SQLDA", 0, "Memory Error");
return(FAILURE);
#ifdef DEBUG
fprintf(fp, " Memory allocation for Select Descriptor succeeded.\n");
fflush(fp);
#endif
Select_da->N = MAX_COLUMN_COUNT;
return(SUCCESS);
int
prepare_sql() {
char msg[256], oraclmsg[256];
int buf_len = 0, msg_len = 0;
| Prepare the Sql statement. |
EXEC SQL
PREPARE sql_stmt
FROM :Sql;
#ifdef DEBUG
fprintf(fp, " Prepared SQL: %s. RC: %d.\n", Sql, sqlca.sqlcode);
fflush(fp);
#endif
if (sqlca.sqlcode != 0) {
buf_len = sizeof(oraclmsg)-1;
sqlglm(oraclmsg, &buf_len, &msg_len);
oraclmsg[msg_len] = '\0';
sprintf(Results, "%9d", sqlca.sqlcode);
error("prepare_sql()", "Parse", sqlca.sqlcode, oraclmsg);
return(FAILURE);
return(SUCCESS);
int
declare_cursor() {
char msg[256], oraclmsg[256];
int buf_len = 0, msg_len = 0;
| Set up the cursor to loop through |
EXEC SQL
DECLARE sql_cursor
CURSOR FOR sql_stmt;
#ifdef DEBUG
fprintf(fp, " Declared cursor. RC: %d\n", sqlca.sqlcode);
fflush(fp);
#endif
if (sqlca.sqlcode != 0) {
buf_len = sizeof( oraclmsg)-1;
sqlglm(oraclmsg, &buf_len, &msg_len);
oraclmsg[msg_len] = '\0';
sprintf(Results, "%9d", sqlca.sqlcode);
error("declare_cursor()", "declare cursor", sqlca.sqlcode, oraclmsg);
return(FAILURE);
return(SUCCESS);
int
open_cursor() {
char msg[256], oraclmsg[256];
int buf_len = 0, msg_len = 0;
| Open the cursor. |
EXEC SQL
OPEN sql_cursor;
#ifdef DEBUG
fprintf(fp, " Opened cursor. RC:%d\n", sqlca.sqlcode);
fflush(fp);
#endif
if (sqlca.sqlcode != 0) {
buf_len = sizeof(oraclmsg)-1;
sqlglm(oraclmsg, &buf_len, &msg_len);
oraclmsg[msg_len] = '\0';
sprintf(Results, "%9d", sqlca.sqlcode);
error("open_cursor()", "open cursor", sqlca.sqlcode, oraclmsg);
return(FAILURE);
return(SUCCESS);
int
describe_select_list() {
char msg[256], oraclmsg[256];
int buf_len = 0, msg_len = 0;
| Get description of columns |
EXEC SQL
DESCRIBE SELECT LIST FOR sql_stmt
INTO Select_da;
#ifdef DEBUG
fprintf(fp, " Described columns. RC %d\n", sqlca.sqlcode);
fflush(fp);
#endif
if (sqlca.sqlcode != 0) {
buf_len = sizeof(oraclmsg)-1;
sqlglm(oraclmsg, &buf_len, &msg_len);
oraclmsg[msg_len] = '\0';
sprintf(Results, "%9d", sqlca.sqlcode);
error("describe_select_list()", "describe select list", sqlca.sqlcode, oraclmsg);
return(FAILURE);
return(SUCCESS);
int
setup_sqlda() {
char buf[MAX_STRING_LENGTH+4];
int done = FALSE, nullok = 0, i = 0;
#ifdef DEBUG
fprintf(fp, " --> Setting up SQLDA.\n");
fflush(fp);
#endif
if (allocate_sqlda() == FAILURE)
return(FAILURE);
if (prepare_sql() == FAILURE)
return(FAILURE);
if (declare_cursor() == FAILURE)
return(FAILURE);
if (open_cursor() == FAILURE)
return(FAILURE);
if (describe_select_list() == FAILURE)
return(FAILURE);
| Too many columns in select list. |
if (Select_da->F < 0) {
strcpy(Results, "000000001");
error("setup_sqlda()", "check select list count", 0, "Too many values in select list");
return(FAILURE);
| Set the number of columns to the actual |
| number of columns. |
Select_da->N = Select_da->F;
| We are going to convert all fields to a string. |
for (i == 0; i < Select_da->F; i++) {
sqlnul(&(Select_da->T), &(Select_da->T[i]), &nullok);
Select_da->T[i] = EXT_STRING;
Select_da->L[i] = MAX_STRING_LENGTH;
| Allocate the result area to be as big as |
| MAX_STRING_LENGTH. |
if ((Select_da->V[i] = malloc(Select_da->L[i])) == NULL) {
#ifdef DEBUG
fprintf(fp, " Allocation of column values failed.\n");
fflush(fp);
#endif
strcpy(Results, "000000001");
error("setup_sqlda()", "allocate column values", 0, "Memory Error");
return(FAILURE);
if ((Select_da->I[i] = (short *) malloc(sizeof(short))) == NULL) {
#ifdef DEBUG
fprintf(fp, " Allocation of idicator values failed.\n");
fflush(fp);
#endif
strcpy(Results, "000000001");
error("setup_sqlda()", "allocate indicator values", 0, "Memory Error");
return(FAILURE);
#ifdef DEBUG
fprintf(fp, " Allocation of memory for values succeeded.\n");
fflush(fp);
#endif
return(SUCCESS);
| add_eom adds the end of message |
| delimiter (an aditional comma). |
int
add_eom() {
char *result_ptr;
if (strlen(Results) >= sizeof(Results) - 1) {
strcpy(Results, "000000001");
error("add_eom()", "Add eom failed. Size overflow", 0, "Memory Error");
return(FAILURE);
result_ptr = &Results[strlen(Results)-1];
while (*result_ptr && (*result_ptr != ','))
result_ptr--;
if (*result_ptr) {
result_ptr++;
*(result_ptr++) = ',';
*result_ptr = '\0';
return(SUCCESS);
int close_cursor() {
char msg[256], oraclmsg[256];
int buf_len = 0, msg_len = 0;
| Close the cursor. |
EXEC SQL
CLOSE sql_cursor;
#ifdef DEBUG
fprintf(fp, " Closing cursor. RC: %d\n", sqlca.sqlcode);
fflush(fp);
#endif
if (sqlca.sqlcode != 0) {
buf_len = sizeof(oraclmsg)-1;
sqlglm(oraclmsg, &buf_len, &msg_len);
oraclmsg[msg_len] = '\0';
error("generate_sql()", "close cursor", sqlca.sqlcode, oraclmsg);
return(FAILURE);
return(SUCCESS);
int
fetch() {
char msg[256], oraclmsg[256];
char buf[MAX_STRING_LENGTH+4];
int buf_len = 0, msg_len = 0;
EXEC SQL
FETCH sql_cursor
USING DESCRIPTOR Select_da;
#ifdef DEBUG
fprintf(fp, " --> Fetching rows. RC %d\n", sqlca.sqlcode);
fflush(fp);
#endif
if (sqlca.sqlcode != 0) {
if (sqlca.sqlcode != NODATAFOUND) {
buf_len = sizeof(oraclmsg)-1;
sqlglm(oraclmsg, &buf_len, &msg_len);
oraclmsg[msg_len] = '\0';
error("fetch()", "Error fetching row.", sqlca.sqlcode, oraclmsg);
return(sqlca.sqlcode);
return(NODATAFOUND);
return(SUCCESS);
| Free up any memory structures. |
void
free_memory() {
int i = 0;
for (i = 0; i < Select_da->F; i++) {
free(Select_da->V[i]);
free(Select_da->I[i]);
| generate_sql() uses the message we received from the queue |
| (a SQL statement) to query the database. We have to use |
| dynamic Sql Version 4 for this type of Sql. The number of |
| columns we are selecting is unknown. This means we can't |
| use the INTO clause. |
int
generate_sql() {
char buf[MAX_STRING_LENGTH+4];
int rc = SUCCESS, done = FALSE, nullok = 0, i = 0;
#ifdef DEBUG
if ((fp = fopen(SQLLOG, "a")) == NULL)
fp = stderr;
#endif
| Connect to the database |
if (connect_db() == FAILURE)
return(FAILURE);
if (setup_sqlda() == FAILURE)
return(FAILURE);
| Place the answer in a comma delimited buffer. |
memset(Results, NULL, sizeof(Results));
done = FALSE;
while (!done) {
rc = fetch();
if (rc != SUCCESS) {
if (Results[0] == '\0')
sprintf(Results, "%9d,", rc);
done = TRUE;
else {
| Put return code of success in first. |
if (Results[0] == '\0')
strcpy(Results, "000000000,");
for (i = 0; i < Select_da->F; i++) {
Select_da->V[i][Select_da->L[i]] = '\0';
| Check to see if the value is null. |
if (*Select_da->I[i] < 0)
strcpy(buf, " ,");
else
sprintf(buf, "%s,", Select_da->V[i]);
if (strlen(Results) + strlen(buf) > sizeof(Results)) {
strcpy(Results, "000000001");
error("generate_sql()", "String concat failed. Size overflow", 0, "Memory Error");
return(FAILURE);
strcat(Results, buf);
#ifdef DEBUG
fprintf(fp, " --> Results %s\n", Results);
fflush(fp);
#endif
| Close the cursor. |
close_cursor();
| Disconnect from the database |
disconnect_db();
| Remove trailing comma. |
if (add_eom() == FAILURE)
return(FAILURE);
#ifdef DEBUG
fflush(fp);
#endif
free_memory();
#ifdef DEBUG
fclose(fp);
#endif
null -
How to (in Pro*C) pass a cursor variable as a pointer between functions
I am opening a cursor in a called function that accepts as one argument a pointer to a cursor variable, and a second argument for the sql string defining the cursor select. That works fine, and in that same function can successfully fetch and access the records from the cursor. However, my objective is to fetch the records in another function that calls the first function. I want to pass back to the calling function the pointer to the cursor variable from the first function. In the second (calling) function, is where I want to fetch the records. What I am getting is SQLCODE = -1002 (fetch out of sequence).
Here is the relevent code in the first called function that calls a PL/SQL package procedure to open the cursor, followed by the code in the second calling procedure where I am attempting to fetch the records:
/******Called function code starts here ******/
EXEC SQL INCLUDE SQLCA;
long db_makeCursor(cursorID, SQLstr)
EXEC SQL BEGIN DECLARE SECTION;
sql_cursor cursorID; / a pointer to a cursor variable */
char *SQLstr;
EXEC SQL END DECLARE SECTION;
long SQLCODE;
EXEC SQL BEGIN DECLARE SECTION;
sql_cursor dbCursor; /* a cursor variable */
EXEC SQL END DECLARE SECTION;
EXEC SQL WHENEVER SQLERROR DO sql_error();
dbCursor = *cursorID;
EXEC SQL EXECUTE
BEGIN
db_util_ref_cursor_pkg.open_dbNameCursor( :dbCursor, :SQLstr );
END;
END-EXEC;
return;
/******Calling function code starts here ******/
EXEC SQL INCLUDE SQLCA;
EXEC SQL BEGIN DECLARE SECTION;
static PROCLOG PROC_Rec;
EXEC SQL END DECLARE SECTION;
long retrieveProcesses( _proclog, sqlForProcLog )
EXEC SQL BEGIN DECLARE SECTION;
PROCLOG _proclog;
char *sqlForProcLog
EXEC SQL END DECLARE SECTION;
long rc;
long SQLCODE;
EXEC SQL BEGIN DECLARE SECTION;
sql_cursor dbCursor; /* a cursor variable */
sql_cursor cursorID; / a pointer to a cursor variable */
PROCLOG proclog;
short end_ts_ind;
short proc_name_ind;
short comments_ind;
EXEC SQL END DECLARE SECTION;
cursorID = &dbCursorName; /* assign a value to the pointer */
EXEC SQL ALLOCATE :dbCursor;
rc = dbUtilities_makeCursor( cursorID, sqlForProcLog);
if (rc == TRUE)
while (SQLCODE == 0)
EXEC SQL FETCH :dbCursorName INTO
:proclog.PROC_ID,
:proclog.START_TS,
:proclog.END_TS:end_ts_ind,
:proclog.PROC_NAME:proc_name_ind,
:proclog.COMMENTS:comments_ind,
if (SQLCODE == 0)
printf("PROC_ID: %d; COMMENTS: %s\n",proclog.PROC_ID, proclog.COMMENTS);
} /* end retrieveProcesses */You need to include a loop...
for i=0;i<sqlca.sqlerrd[2];i++)
printf("name %s\n", struct.name)
This allows you to step through your cursor records!!! -
How to pass a litral string into cursor variable?
Hi All
I have a code like below:
I need to select the following table,column with the criteria as such but it looks like the literal string does not work for cursor variable.
I can run the SQL in sqlplus but how I can embed that in PL/SQL code??
-Thanks so much for the help
cursor ccol2(Y1 varchar2) is select table_name,column_name from user_tab_columns
where table_name like 'HPP2TT%' and table_name like '%Y1'
and column_name not in ('MEMBERID');Literal strings are fine in a cursor, however, your logic is likely wrong, and you are not using the Y1 parameter to the cursor correctly. If you are looking for tables that either start with HPP2TT or end with Y1 (whatever you pass as Y1), then you need something more like:
cursor ccol2(Y1 varchar2) is
select table_name, column_name
from user_tab_columns
where (table_name like 'HPP2TT%' or
table_name like '%'||Y1) and
column_name not in ('MEMBERID');In the unlikely event that you are lookig for table that actually do start with HPP2TT and end in whatever is passed in Y1 then your query could be simplified to:
cursor ccol2(Y1 varchar2) is
select table_name, column_name
from user_tab_columns
where table_name like 'HPP2TT%'||Y1 and
column_name not in ('MEMBERID');Note in both cases, a single member in-list is bad practice, although Oracle will transform it to an equality predicate instead.
John -
How to inspect a cursor variable in a debug session?
In a function inside the body of a package I do...
Example:
V_SITUACIONESACTYHIST C_SITUACIONESACTYHIST%ROWTYPE;
BEGIN
FOR v_SituacionesACTyHIST IN c_SituacionesACTyHIST( p_id_DECE400, p_idpers )
LOOP
IF ( V_SITUACIONESACTYHIST.ESTADO_SITUACION = 'S' ) THEN
v_hay_regs_hist:=1;
END IF;
END LOOP;
where the cursor variable c_SituacionesACTyHIST is declared in the specifications package (Is this the problem, because is a global declaration?).
When debugging I cannot inspect the value of V_SITUACIONESACTYHIST.ESTADO_SITUACION or whatever cursor variable field; I always obtain "NULL" as value...
Why?
How can I see the value of that variables?
I have the same problem in v2.1 and 1.5.5 version of sqldeveloper.
Thanks.
Edited by: pacoKAS on 11-feb-2010 0:14
Edited by: pacoKAS on 11-feb-2010 0:17
Edited by: pacoKAS on 11-feb-2010 0:17
Edited by: pacoKAS on 11-feb-2010 0:19
Edited by: pacoKAS on 11-feb-2010 0:21
Edited by: pacoKAS on 11-feb-2010 0:22
Edited by: pacoKAS on 11-feb-2010 0:22I'm proposing that you don't have a variable named the same as your cursor variable.
CREATE OR REPLACE
PROCEDURE P1
AS
CURSOR test_cur
IS
SELECT owner, table_name FROM all_tables WHERE ROWNUM <= 10;
-- x test_cur%rowtype; /* This variable is not needed. */
BEGIN
FOR x IN test_cur /* If you don't have another variable named x somewhere, you can see values for x */
LOOP
dbms_output.put_line(x.owner || '.' || x.table_name);
END LOOP;
END P1;from your example...
V_SITUACIONESACTYHIST C_SITUACIONESACTYHIST%ROWTYPE;
BEGIN
FOR v_SituacionesACTyHIST IN c_SituacionesACTyHIST( p_id_DECE400, p_idpers )
LOOP
IF ( V_SITUACIONESACTYHIST.ESTADO_SITUACION = 'S' ) THEN
v_hay_regs_hist:=1;
END IF;
END LOOP;You're declaring your variable twice:
(1) V_SITUACIONESACTYHIST C_SITUACIONESACTYHIST%ROWTYPE;
(2) FOR v_SituacionesACTyHIST IN c_SituacionesACTyHIST
When you're debugging, it's looking at the first version...which is null because you haven't assigned anything to it. When you use a Cursor For-Loop like that, it implicitly declares the variable for you. You don't have to do it in your DECLARE section.
Edited by: DylanB123 on Feb 16, 2010 1:04 PM -
Cursor variable in a Java program
Hi all,
I would like to know is how to explicitly pass a cursor variable to a stored procedure after defining it in the java source and to get the result back to the same variable.
An example would be appreciated.
Thanks in advance
GiridharI think java profiler can do the job. There are sharewares i know of like JSprint and JProfiler.
-
Getting error in cursor variable in CallableStatement
Hi,
I am trying to retrieve result set from PL/SQL procedure using cursor variable.
but I getting error sometime.
this is code in my program...
CallableStatement pstmt=null;
pstmt = con.prepareCall("{call Crms2.SearchRNameTime(?,?,?,?,?,?)}");
pstmt.setString(1, uid);
pstmt.setString(2, strBookingDate);
pstmt.setInt(3, roomid);
pstmt.setInt(4, lngStartTime);
pstmt.setInt(5, lngEndTime);
pstmt.registerOutParameter(6, oracle.jdbc.driver.OracleTypes.CURSOR ); // error accured in this line
pstmt.execute();
rs = (ResultSet)pstmt.getObject(6);
error was accrued at line : pstmt.registerOutParameter(6, oracle.jdbc.driver.OracleTypes.CURSOR );
error is: orable.jdbc.driver can not resolve tha symbol..
but it some time executing , some time giving error.
it is require any package to import?
please help me on this problem.
regards
Narru990187 wrote:
i have created a cursor to return only 5th row from a table .
declare
cursor cur is select * From(select last_name,salary,rownum rn from employees where rownum<=50)) where rn=5;
just a side note, (others have helped with the actual error already), using "rownum" like you do isn't very consistent. Not really sure about the requirment of "5th row", but no matter. Just keep in mind that the way Oracle assigns a rownum, and the fact you have no sorting/order ... you are - effectively - getting a random row. That is, with no data changing, Oracle may very well retrieve things in a different order due to index, new oracle version, whatever.
If you do actually need the 5th row where you have some sorting (ie 5th largest salary, or 5th record by last name, etc. ), then you may want to consider something like:
select * from (select last_name, salary, row_number() over (order by salary desc) rn from employees) where rn = 5;
or whatever your sort criteria is. Do a search for "Top N" queries if you need more info.
It'll work a bit more consistently. -
Obtaining a weakly typed cursor variable's field list
In a situation where a weakly typed cursor variable is passed to a procedure, after having been previously opened, is there any way to find out what the field names or aliases are that make up the underlying cursor? Is this information available in some dynamic view?
Try:
select view_name from dba_views where view_name like '%CURSOR%';
The views you may be interested in are gv_$open_cursor and v_$open_cursor. Both have a column named SQL_TEXT that will at least give the statement the cursor is executing.
Hope this helps. -
Hello,
I have a procedure, which specification is something like that:
procedure proc1 (pcursor OUT SYS_REFCURSOR, parg1 IN NUMBER, parg2 IN NUMBER, ...);Inside the body of proc1 I have
OPEN pcursor FOR
SELECT column1,
column2,
CURSOR (SELECT column1, column2
FROM table2
WHERE <some clauses come here>) icursor1
FROM table1
WHERE <some clauses come here>;In a PL/SQL block I would like to execute proc1 and then to fetch from pcursor. This is what I am doing so far:
DECLARE
ldata SYS_REFCURSOR;
larg1 NUMBER := 123;
larg2 NUMBER := 456;
outcolumn1 dbms_sql.Number_Table;
outcolumn2 dbms_sql.Number_Table;
BEGIN
some_package_name.proc1 (ldata, larg1, larg2, ...);
FETCH ldata BULK COLLECT INTO
outcolumn1, outcolumn2,..., *and here is my problem*;
END;
/How can I rewrite this in order to get the content of icursor1 ?
Thanks a lot!Verdi wrote:
How can I rewrite this in order to get the content of icursor1 ?
Firstly ref cursors contain no data they are not result sets but pointers to compiled SQL statements.
Re: OPEN cursor for large query
PL/SQL 101 : Understanding Ref Cursors
Ref cursors are not supposed to be used within PL/SQL or SQL for that matter, though people keep on insisting on doing this for some reason.
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/static.htm#CIHCJBJJ
Purpose of Cursor Variables
You use cursor variables to pass query result sets between PL/SQL stored subprograms and their clients. This is possible because PL/SQL and its clients share a pointer to the work area where the result set is stored.A ref cursor is supposed to be passed back to a procedural client language, such as Java or .Net.
If you want to re-use a SQL statement in multiple other PL/SQL or SQL statements you would use a view. -
Is IN OUT for Cursor variable mandatory?
Hi all:
I have a stored procedure which will just return a boolean value after the task is done. And i'm using more than 1 cursor variables in that stored procedure. What my question is
"Is IN OUT for Cursor variable mandatory from the PROCEDURE i have written?".
Because in the manual they mentioned that IN OUT should be there for a cursor variable. My PROCEDURE declaration is as below:
TYPE emp_det IS REF CURSOR;
PROCEDURE <proc_name>(startdate VARCHAR2, enddate VARCHAR2, ids VARCHAR2, taskdone OUT BOOLEAN,emp IN OUT emp_det);
Is there any modification in the above declaration if i'm using one cursor and NOT returning that cursor back to the called program. I don't to get returned.
Hope i made it clear.
Thanks,
- VenuVenu:
As far as I know you don't need In Out unless
you are using that variable to pass values between the two procedures.
It is so easy to try it , so I suggest you write two small procedures to check this.It should only take a couple of minutes.
Hope this helps. -
Indicator Variable ( for Pro*C) support stop in Oracle10
It is said that Oracle will stop the support of treating NULL through the indicator variable in Pro*C( from Oracle 10g). How will then we'll be hanling NULL ( besides NVL or DECODE ) specially if NULL is to be distinguihed from 0 in numeric cases. Also while inserting into the database what indicatiion can be done so that Oracle knows its a NULL value
Hari
This forum is for queries related to the Oracle JDeveloper Application Migration Assistant tool. I am not aware of any changes in PRO*C around indicator variables. In fact, there is no reference to this in any of 10g docs. See http://download-west.oracle.com/docs/cd/B12037_01/appdev.101/a97269/pc_02prc.htm#sthref129
I would suggest for further clarity to post this article to the database forum on http://otn.oracle.com/forums/database.html
cheers
Jan -
Return cursor variable in function
I have three different sql queries already joined to diff tables, like query1 is made by joining 4 diff tables.
query1----select a,b,c,x from t1(set of 4 tables)
query2----select e,f from t2(set of 3 tables) where t1.x=t2.x
query3----select g,h from t3(set of 3 tables) where t1.x=t3.x
I need to return the resultset on a single row something like this_
a,b,c,x,e,f,g,h
I am using the above queries in a function and to return the result set using cursor variable as the return type for the function.
Please suggest a suitable solution design.
Thanks.I have only single column in query1 which is referencing to query2 and query 3. So further joining them is not preferred. There is no escape from joining them. It will probably be the most effective solution.
That said you might consider to restructure/review your whole involved select(s).
Translating Laurents proposition to your nomenclature you could finally end up with something like
CREATE FUNCTION f (p_st your_data_type)
RETURN sys_refcursor
AS
BEGIN
OPEN cur FOR
SELECT *
FROM query1, query2, query3
WHERE st = p_st AND query1.ID = query2.ID AND query1.ID = query3.ID;
RETURN cur;
END; -
Cursor variable persistence (or lack of) - workarounds ?
Using 11.1.0.7; want to be able to pass a query SQL statement out of a client to a database package and have the package execute the query and return N rows out of the query, and later serve requests from client for the next N records etc. Having opened the cursor I then want to be able to retain a reference to it for the secondary / subsequent look-ups. The restrictions on package cursor variable definition prevent the obvious solution(s). Wondering whether others had experience of delivering such a solution ?
Have trialled use of DBMS_SQL, but under 11g run into restrictions relating to new 11g security features, which the docco suggests can be disabled, but reluctant to do so. Returning the cursor reference to client (Oracle Forms) could be the next option, but would prefer to not. Figured this might've already been solved ...?
Thanks,robli wrote:
I can pass the ref cursor back to the client but there's no way to otherwise persist the ref cursor in the database session - true ?Yes you can persist ref cursors in 11g:
SQL> --// custom data type for storing DBMS_SQL cursor handles
SQL> create or replace type TCursorList is table of number;
2 /
Type created.
SQL> --// our interface for storing (persisting) ref cursor handles in PL/SQ:
SQL> create or replace package CursorContainer as
2 --// store a ref cursor (and get an index number in return to
3 --// access that ref cursor again)
4 procedure StoreRefCursor( c in out sys_refcursor, idx out number );
5
6 --// retrieve a stored ref cursor handle
7 function GetRefCursor( idx number ) return sys_refcursor;
8
9 function CursorList return TCursorList;
10 end;
11 /
Package created.
SQL>
SQL> create or replace package body CursorContainer as
2 --// actual variable/collection that contains the handles
3 cursors TCursorList;
4
5 procedure StoreRefCursor( c in out sys_refcursor, idx out number ) is
6 begin
7 if cursors is null then
8 cursors := new TCursorList();
9 end if;
10
11 cursors.Extend(1);
12 cursors( cursors.Count ) := DBMS_SQL.To_Cursor_Number( c );
13
14 idx := cursors.Count;
15 end;
16
17 function GetRefCursor( idx number ) return sys_refcursor is
18 begin
19 return(
20 DBMS_SQL.To_RefCursor(
21 cursors( idx )
22 )
23 );
24 end;
25
26 function CursorList return TCursorList is
27 begin
28 return( cursors );
29 end;
30
31 end;
32 /
Package body created.
SQL>
SQL> --// create and store 2 ref cursors
SQL> declare
2 c1 sys_refcursor;
3 c2 sys_refcursor;
4 n number;
5 begin
6 open c1 for select sysdate from dual;
7 open c2 for select rownum, d.dummy from dual d;
8
9 CursorContainer.StoreRefCursor( c1, n );
10 CursorContainer.StoreRefCursor( c2, n );
11 end;
12 /
PL/SQL procedure successfully completed.
SQL>
SQL> --// what handles did we store?
SQL> select column_value as CURSOR_HANDLE from TABLE(CursorContainer.CursorList);
CURSOR_HANDLE
388610362
54290194
SQL>
SQL> --// we define a ref cursor pointer on the client side
SQL> var c refcursor
SQL> --// okay, we now consume these stored ref cursor handles
SQL> --// grab cursor 1, consume and close it
SQL> exec :c := CursorContainer.GetRefCursor(1);
PL/SQL procedure successfully completed.
SQL> print :c
SYSDATE
2011-03-02 13:56:22
SQL>
SQL> --// grab cursor 2, consume and close it
SQL> exec :c := CursorContainer.GetRefCursor(2);
PL/SQL procedure successfully completed.
SQL> print :c
ROWNUM DUM
1 X
SQL> I would however question such an interface for storing ref cursor handles... I have never in many years of Oracle client-server and PL/SQL development, ran into the requirement to persist ref cursor handles in PL/SQL(either for later consumption in PL/SQL, or consumption by an external client).
The approach does not sound very robust to me. -
Cursor variable and for update
hi
can anyone explain me why can't we use "for update " with a Cursor Variable.
Thanks in advance.user10314274 wrote:
exmple : I read it in one book(Oracle press)And how difficult is it to test this?
declare
v_cur sys_refcursor;
v_ename varchar2(20);
begin
open v_cur for select ename from emp for update;
loop
fetch v_cur into v_ename;
exit when v_cur%notfound;
dbms_output.put_line(v_ename);
end loop;
close v_cur;
dbms_output.put_line('----------------------');
open v_cur for 'select ename from emp for update';
loop
fetch v_cur into v_ename;
exit when v_cur%notfound;
dbms_output.put_line(v_ename);
end loop;
close v_cur;
end;
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
PL/SQL procedure successfully completed.
SQL> SY. -
Migration Workbench Ver 1.2.2 has migrated an SQL Server 6.5
strored procedure as a package containing only the Cursor
variable and a procedure with INOUT parameter with packaged
cusorvariable as one of the parameters to Oracle 8.0.5.
How do you execute this procedure from SQL + and from another
PL/SQL block where you have to retrive the data elements of the
cursor.(ie.How do you input the cursor variable parameter in the
EXECUTE stored procedure command.)An example of the type is
appreciated.
nullSurendra,
Using refcursors between procedures is covered in the 'Wrong
number or types of argument in call to stored proc' 4 jun thread,
with reference to the manuals.
Using refcursor bind variables is covered in the sqlplus user
guide and reference reproduced below (from the 8.1.5 version,
also in 8.0.5) available on line on OTN.
Hope that helps,
Turloch
Oracle Migration Workbench Team
Using REFCURSOR Bind Variables
SQL*Plus REFCURSOR bind variables allow SQL*Plus to fetch and
format the results of a SELECT statement contained in a PL/SQL
block.
REFCURSOR bind variables can also be used to reference PL/SQL
cursor variables in stored procedures. This allows you to store
SELECT statements in the database and reference them from
SQL*Plus.
A REFCURSOR bind variable can also be returned from a stored
function.
Note:
You must have Oracle7, Release 7.3 or above to assign
the return value of a stored function to a
REFCURSOR variable.
Example 3-18 Creating, Referencing, and Displaying REFCURSOR Bind
Variables
To create, reference and display a REFCURSOR bind variable, first
declare a local bind variable of the REFCURSOR datatype
SQL> VARIABLE dept_sel REFCURSOR
Next, enter a PL/SQL block that uses the bind variable in an OPEN
... FOR SELECT statement. This statement opens a cursor variable
and executes a query. See the PL/SQL User's Guide and Reference
for information on the OPEN command and cursor variables.
In this example we are binding the SQL*Plus dept_sel bind
variable to the cursor variable.
SQL> BEGIN
2 OPEN :dept_sel FOR SELECT * FROM DEPT;
3 END;
4 /
PL/SQL procedure successfully completed.
The results from the SELECT statement can now be displayed in
SQL*Plus with the PRINT command.
SQL> PRINT dept_sel
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
The PRINT statement also closes the cursor. To reprint the
results, the PL/SQL block must be executed again before using
PRINT.
Example 3-19 Using REFCURSOR Variables in Stored Procedures
A REFCURSOR bind variable is passed as a parameter to a
procedure. The parameter has a REF CURSOR type. First, define the
type.
SQL> CREATE OR REPLACE PACKAGE cv_types AS
2 TYPE DeptCurTyp is REF CURSOR RETURN dept%ROWTYPE;
3 END cv_types;
4 /
Package created.
Next, create the stored procedure containing an OPEN ... FOR
SELECT statement.
SQL> CREATE OR REPLACE PROCEDURE dept_rpt
2 (dept_cv IN OUT cv_types.DeptCurTyp) AS
3 BEGIN
4 OPEN dept_cv FOR SELECT * FROM DEPT;
5 END;
6 /
Procedure successfully completed.
Execute the procedure with a SQL*Plus bind variable as the
parameter.
SQL> VARIABLE odcv REFCURSOR
SQL> EXECUTE dept_rpt(:odcv)
PL/SQL procedure successfully completed.
Now print the bind variable.
SQL> PRINT odcv
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
The procedure can be executed multiple times using the same or a
different REFCURSOR bind variable.
SQL> VARIABLE pcv REFCURSOR
SQL> EXECUTE dept_rpt(:pcv)
PL/SQL procedure successfully completed.
SQL> PRINT pcv
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Example 3-20 Using REFCURSOR Variables in Stored Functions
Create a stored function containing an OPEN ... FOR SELECT
statement:
SQL> CREATE OR REPLACE FUNCTION dept_fn RETURN -
cv_types.DeptCurTyp IS2 resultset cv_types.DeptCurTyp;
3 BEGIN
4 OPEN resultset FOR SELECT * FROM DEPT;
5 RETURN(resultset);
6 END;
7 /
Function created.
Execute the function.
SQL> VARIABLE rc REFCURSOR
SQL> EXECUTE :rc := dept_fn
PL/SQL procedure successfully completed.
Now print the bind variable.
SQL> PRINT rc
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
4 rows selected
The function can be executed multiple times using the same or a
different REFCURSOR bind variable.
SQL> EXECUTE :rc := dept_fn
PL/SQL procedure successfully completed.
SQL> PRINT rc
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Surendra Kumar (guest) wrote:
: Migration Workbench Ver 1.2.2 has migrated an SQL Server 6.5
: strored procedure as a package containing only the Cursor
: variable and a procedure with INOUT parameter with packaged
: cusorvariable as one of the parameters to Oracle 8.0.5.
: How do you execute this procedure from SQL + and from
another
: PL/SQL block where you have to retrive the data elements of the
: cursor.(ie.How do you input the cursor variable parameter in
the
: EXECUTE stored procedure command.)An example of the type is
: appreciated.
Oracle Technology Network
http://technet.oracle.com
null
Maybe you are looking for
-
Recently I rebuilt my PC to handle after effects a little better. I am running CS3 on windows XP 64 bit, however once I start working on a project for less than 30 minutes my system locks up and brings up the blue screen of death. It gives me a "Page
-
My ipad has gone into recovery mode after an "error occured" whilst trying to update it. Will it come out of recovery on it's own? There is a lot of data I want to save before restoring it to factory settings
-
Trying to understand traffic Flow in a LWAPP wireless configuration.
I'm trying to understand at a high level how wireless traffic flow in the new LWAPP configuration. Based on what I can tell all wireless traffic must flow through the controllers prior to getting onto the LAN. So lets say I have a LWAPP Access Point
-
ManagedBean and Bind Variables in ADF applications
Situation with Target Unreachable, 'TestBean'. ManagedBean: TestBean, parameter objectId ViewObject: sql-based: select * from someobject where id = :objectId Unbounded taskflow with the one page: Start.jspx Bounded TaskFlow "TestTaskFlow" with pagefr
-
Disk partition on macbook air, disk partition on macbook air
how disk partition is working on macbook air?