Open cursor for dynamic sql
Hi
I am using oracle 8.1.7 on solaris.
I have created
SQL> CREATE OR REPLACE PACKAGE TEST_PKG AS
2 TYPE row_cursor IS REF CURSOR RETURN TEMP_TAB%ROWTYPE;
3 PROCEDURE Return_Columns_proc (c_return IN OUT row_cursor);
4 END TEST_PKG;
5 /
Package created.
now i am trying to create the procedure Return_Columns_proc by
CREATE OR REPLACE PACKAGE BODY TEST_PKG AS
PROCEDURE Return_Columns_proc (c_return IN OUT row_cursor) AS
QUERY_STR VARCHAR2(850);
x number ;
BEGIN
x:=1;
QUERY_STR :='SELECT * FROM temp_tab where order_line_id = '||x;
OPEN c_return FOR QUERY_STR;
END Return_Columns_proc;
END TEST_PKG;
I am getting following error.
SQL> show error
Errors for PACKAGE BODY TEST_PKG:
LINE/COL ERROR
8/4 PL/SQL: Statement ignored
8/9 PLS-00455: cursor 'C_RETURN' cannot be used in dynamic SQL OPEN
statement
any help for this error.
The error says it all. You have defined a strong ref cursor and it cannot be used with dynamic sql. However, that does not mean you cannot use the query directly in the OPEN clause
OPEN c_Return FOR SELECT * FROM temp_tab where order_line_id = X ;
Similar Messages
-
How can I open a cursor for dynamic sql statement
Hi,
I'm facing issues opening a cursor for dynamic sql statement : PLS-00455: cursor 'RESULT1' cannot be used in dynamic SQL OPEN statement.
CREATE OR REPLACE FUNCTION DEMO
(MN_I in VARCHAR)
return AB_OWNER.ABC_Type.NonCurTyp is
RESULT1 AB_OWNER.ABC_Type.NonCurTyp;
sql_stmt VARCHAR2(4000);
BEGIN
sql_stmt := 'SELECT * FROM AB_OWNER.DUN WHERE JZ_I in ('||mn_i||') ORDER BY app.ACC_I';
OPEN RESULT1 FOR sql_stmt;
END IF;
return RESULT1;
END DEMO;
What changes should I make in the code so that it doesn't fail? I can't change the definition of RESULT1 cursor though.Gangadhar Reddy wrote:
I used SYS REFCURSOR and was able to implement successfully.How many times did you run this successful implementation that does not use bind variables?
Because this is what will happen when it runs a lot.
http://download.oracle.com/docs/cd/E11882_01/server.112/e17766/e2100.htm#sthref1874
http://forums.oracle.com/forums/search.jspa?q=%2BORA-04031%20%2Bbind&objID=c84&dateRange=all&rankBy=10001&start=30
And you will have to regularly restart the server, or possibly slightly less invasive, flush the shared pool.
Flushing Shared Pool regularly
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1516005546092
>
Ok, this is an easy one to diagnose.
You are not using bind variables. This is terrible. Flushing the shared pool is a bad
solution -- you are literally killing the performance on your box by not using them.
If I was to write a book on how to build non scalable applications in Oracle, this
would be the first and last chapter. This is a major cause of performance issues and a
major inhibitor of scalability in Oracle. The way the Oracle shared pool (a very
important shared memory data structure) operates is predicated on developers using bind
variables. If you want to make Oracle run slowly, even grind to a total halt just
refuse to use them.
>
But, please feel free to go ahead with this successful implementation.
I just hope anyone else who reads this doesn't make the same mistake. -
Open SYS_REFCURSOR for DYNAMIC SQL
Hi!
I have stored procedure like below:
CREATE OR REPLACE
PROCEDURE MYPROCEDURE
cv_r OUT SYS_REFCURSOR
AS
lv_ExecuteString varchar(2000);
BEGIN
lv_ExecuteString := 'select 1 from dual';
open cv_r for lv_ExecuteString;
END MYPROCEDURE;and then
SQL> var y refcursor
SQL> execute myprocedure(:y);
BEGIN myprocedure(:y); END;
ERROR at line 1:
ORA-00911: invalid character
ORA-06512: at "BPATEL.MYPROCEDURE", line 9
ORA-06512: at line 1shouldnt it suppose to work??? If not then How can I fill up OUT SYS_REFCURSOR with dynamic sql string ???
although If I modify this below in my stored procedure it works fine:
-- open cv_r for lv_ExecuteString;
open cv_r for select 1 from dual;
SQL> var y refcursor
SQL> execute myprocedure(:y);
PL/SQL procedure successfully completed.
SQL> print y
1
1any idea?? why is it doing so???What version are you on? Works fine for me....
ME_XE?CREATE OR REPLACE
2 PROCEDURE MYPROCEDURE
3 (
4 cv_r OUT SYS_REFCURSOR
5 )
6 AS
7 lv_ExecuteString varchar(2000);
8 BEGIN
9 lv_ExecuteString := 'select 1 from dual';
10 open cv_r for lv_ExecuteString;
11 END MYPROCEDURE;
12 /
Procedure created.
Elapsed: 00:00:00.71
ME_XE?var y refcursor
ME_XE?execute myprocedure(:y);
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.03
ME_XE?print :y
1
1
1 row selected.
Elapsed: 00:00:00.00
ME_XE?@version
BANNER
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
PL/SQL Release 10.2.0.1.0 - Production
CORE 10.2.0.1.0 Production
TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
NLSRTL Version 10.2.0.1.0 - Production
5 rows selected.
Elapsed: 00:00:00.10 -
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. -
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 -
SELECT DISTINCT With OPEN cursor FOR
Hello.
I have the following procedure. All it does is open a cursor for an SQL string passed into it, and return the open cursor.
PROCEDURE sp_execute_dynamic (hold_input_string IN CLOB,
hold_cursor OUT hold_cursor_type) IS
BEGIN
OPEN hold_cursor FOR TO_CHAR(hold_input_string);
END sp_execute_dynamic;
It works fine except when I perform SELECT DISTINCT. I get the following error.
SQL> declare
2 TYPE hold_cursor_type IS REF CURSOR;
3 hold_cursor hold_cursor_type;
4 hold_object_name VARCHAR2(1024);
5 hold_object_type VARCHAR2(1024);
6 begin
7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
8 loop
9 fetch hold_cursor into hold_object_name, hold_object_type;
10 exit when hold_cursor%NOTFOUND;
11 dbms_output.put_line('Object Name = '||hold_object_name||' Object Type = '||hold_object_type);
12 end loop;
13 end;
14 /
declare
ERROR at line 1:
ORA-01007: variable not in select list
ORA-06512: at line 9
It does the same thing with SELECT UNIQUE or SELECT with a GROUP BY. Can anyone tell me why this happens and what I could to to work around it?
Thanks
Chrissee at line 7 you are selecting only one column and at line 9you are fetching into two variables
7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
8 loop
9 fetch hold_cursor into hold_object_name, hold_object_type;
HTH -
Help required in changing to str for dynamic sql
Hi
I am trying to make this to string for dynamic sql, this is a part of the sql which is giving problem with p_..as parameters from proc. Help me in this , iam also seeing dbms _output but stil unable to format it to required error free string.
|| ' AND ( po.abbreviationprojectopportid LIKE '
|| '%'
|| 'NVL'
|| '('
|| p_opp_code
|| ', ''NULL'')'
|| '%'
|| ' OR co.companyname LIKE '
|| '%'
|| 'NVL'
|| '('
|| p_client_name
|| ', '' NULL'')'
|| '%'
|| ' OR le.line_item_amount = NVL '
|| ' ('
|| p_booking_amt
|| ', -0.197) '
|| 'OR po.dealcurrency = NVL '
|| '('
|| p_currency
|| ',''NULL'')'
|| 'OR be.booking_entry_id LIKE '
|| '%'
|| 'NVL ('
|| p_entry_id
|| ',''NULL'')'
|| '%'
|| ' OR le.line_item_id LIKE '
|| '%'
|| 'NVL ('
|| p_line_item
|| ',''null'')'
|| '%'
|| ' OR be.ticket_num LIKE '
|| '%'
|| 'NVL ('
|| p_ticket_num
|| ',''NULL'')'
|| '%'
|| ' OR be.updatedby LIKE '
|| '%'
|| 'NVL ('
|| p_user_name
|| ',''NULL'')'
|| '%'
|| ' OR credittransaction.acct_code ='
|| 'NVL ('
|| p_gl_account
|| ','
|| '-0.197)'
|| 'OR debittransaction.acct_code ='
|| 'NVL ('
|| p_gl_account
|| ', '
|| '-0.197) '
|| 'OR credittransaction.profit_ctr_code ='
|| 'NVL ('
|| p_profit_center
|| ','
|| ' -0.197)'
|| 'OR debittransaction.profit_ctr_code ='
|| 'NVL ('
|| p_profit_center
|| ','
|| '-0.197)'
|| ' OR le.sap_posting = NVL ('
|| p_sap_posting
|| ',''$'')'
|| 'OR cmis.cmis_code = NVL ('
|| p_cmis_nominal
|| ','' -0.197)'
|| 'OR sa.sap_code = NVL ('
|| p_sap_booking_entity
|| ', -0.197)'
|| ' OR (be.booking_date BETWEEN '
|| v_booking_date_from
|| 'AND '
|| v_booking_date_to
|| ')'
|| ' )'
|| 'ORDER BY '
|| p_sort_by
|| ' '
|| p_order;some errors.. Try this...
' SELECT be.booking_date bookingdate, '
|| ' be.booking_entry_id entryid, le.line_item_id itemid,'
|| ' po.abbreviationprojectopportid opportunitycode,'
|| ' co.companyname clientname, '
|| ' le.line_item_amount bookingamount,'
|| ' be.ticket_num ticketnum, po.dealcurrency currency,'
|| ' cmis.cmis_code cmis_nominal,'
|| ' sa.sap_code sap_booking_entity,'
|| ' (SELECT full_name '
|| ' FROM iba_employee '
|| ' WHERE TO_CHAR (employeeid) = be.updatedby) updatedby,'
|| ' be.updateddate updateddate, '
|| ' (SELECT le.line_item_amount * rate '
|| ' FROM iba_currencyconversion '
|| ' WHERE tocurrencycd = '
|| 'USD'
|| ' AND currencycd = po.dealcurrency '
|| ' AND conversiondate = be.booking_date) amountusd,'
|| 'debittransaction.acct_code debitglaccount,'
|| ' credittransaction.acct_code creditglaccount,'
|| ' debittransaction.profit_ctr_code debitprofitcenter,'
|| ' credittransaction.profit_ctr_code creditprofitcenter,'
|| ' debittransaction.amt debitamount,'
|| ' credittransaction.amt creditamount'
|| ' FROM rb_booking_entry be, '
|| ' rb_line_item le, '
|| ' rb_booking_period bp,'
|| ' rb_cmis_gl_account cmisgl,'
|| ' rb_cmis_account cmis,'
|| ' iba_projectopportunity po,'
|| ' iba_company co,'
|| ' rb_sap_account sa,'
|| ' (SELECT acctr.line_item_id line_item,'
|| ' sapgl_acc.account_code acct_code,'
|| ' acctr.amount amt,'
|| ' sappr.profit_center_code profit_ctr_code'
|| ' FROM rb_account_transaction acctr,'
|| ' rb_sap_profit_center sappr,'
|| ' rb_sap_gl_account sapgl_acc'
|| ' WHERE acctr.profit_center_id = sappr.profit_center_id '
|| ' AND acctr.gl_account_id = sapgl_acc.gl_account_id '
|| ' AND acctr.transaction_type = ''D'') debittransaction,'
|| ' (SELECT acctr.line_item_id line_item,'
|| ' sapgl_acc.account_code acct_code,'
|| ' acctr.amount amt,'
|| ' sappr.profit_center_code profit_ctr_code '
|| ' FROM rb_account_transaction acctr, '
|| ' rb_sap_profit_center sappr, '
|| ' rb_sap_gl_account sapgl_acc '
|| ' WHERE acctr.profit_center_id =sappr.profit_center_id '
|| ' AND acctr.gl_account_id = sapgl_acc.gl_account_id '
|| ' AND acctr.transaction_type = ''C'') credittransaction '
|| ' WHERE po.projectopportunityid = be.projectopportunityid '
|| ' AND be.booking_entry_id = le.booking_entry_id '
|| ' AND po.companyid = co.companyid '
|| ' AND bp.booking_period_id = be.booking_period_id '
|| ' AND cmis.cmis_id = cmisgl.cmis_id '
|| ' AND le.sap_id = sa.sap_id '
|| ' AND le.cmis_id = cmis.cmis_id '
|| ' AND debittransaction.line_item(+) = le.line_item_id '
|| ' AND credittransaction.line_item(+) = le.line_item_id '
|| ' AND ( po.abbreviationprojectopportid LIKE ' || '''%' || NVL(p_opp_code,'NULL') || '%'''
|| ' OR le.line_item_id LIKE '
|| '''%'
|| NVL (
|| p_line_item
|| ,'null')
|| '%'''
| ' OR le.line_item_amount = '
||NVL(|| p_booking_amt, -0.197)
|| ' OR po.dealcurrency ='
|| NVL(p_currency,'NULL')
|| ' OR be.booking_entry_id LIKE '
|| '''%'
|| NVL (p_entry_id,'NULL')
|| '%'''
|| ' OR be.ticket_num LIKE '
|| '''%'
|| NVL (p_ticket_num,'NULL')
|| '%'''
|| ' OR be.updatedby LIKE '
|| '''%'
|| NVL (p_user_name,'NULL')
|| '%'''
|| ' OR credittransaction.acct_code ='
|| NVL (p_gl_account,-0.197)
|| ' OR debittransaction.acct_code ='
|| NVL (p_gl_account, -0.197)
|| ' OR credittransaction.profit_ctr_code ='
|| NVL (p_profit_center, -0.197)
|| ' OR debittransaction.profit_ctr_code ='
|| NVL (p_profit_center, -0.197)
|| ' OR le.sap_posting = '
||NVL (p_sap_posting,'$')
|| ' OR cmis.cmis_code = '
||NVL (p_cmis_nominal, -0.197)
|| ' OR sa.sap_code = '
|| NVL (p_sap_booking_entity, -0.197)
|| ' OR (be.booking_date BETWEEN to_date('''
|| v_booking_date_from
|| ''') AND to_date('''
|| v_booking_date_to
|| ''')'
|| ' OR co.companyname LIKE '
|| '''%'
|| NVL(p_client_name,'NULL')
|| '%'''
|| ' )'
|| 'ORDER BY ' || p_sort_by || ',' || p_order; -
Open cursor for ...using...
Hi all
1 general question- can someone explain me how 'using keyword in 'open cursor for ...' statement works.
Does it replace where clause and how?
open cur_xx for qry_xxx using text_xxx
where 'text_xxx' is going to be my codition in select statement
Tahnks everyonehttp://oraclesvca2.oracle.com/docs/cd/B10501_01/appdev.920/a96624/13_elems35.htm
-
Open cursor for a dynamic query
Hi,
I'm using forms6i and db 10g
I want to create a procedure like below
PROCEDURE pop_cursor (generic_cur IN OUT gencurtyp, querystring varchar2) IS
BEGIN
OPEN generic_cur FOR querystring;
END;where generic_cur is a Ref Cursor and querystring will contain a query statement like 'select col1... from table1'
The above way i'm not able to do that, i'm getting error
Encountered the symbol 'QUERYSTRING' when expecting on of the following:
select
Is there any alternative??
Please helpYou can only use that sort of dynamic sql in the database. maybe you can return the ref cursor to the form from a db-function, i don't know if it works in forms 6i.
But you could tell us your requirement, maybe you can implement it without these dynamic things. -
Procedure Problem - Open Cursor for SQL
in my form I added a procedure. this is working fine in SQL but when I try to run through form it gives error.
Code of Procedure:-
PROCEDURE Proc_Purchase_all IS
BEGIN
declare
v_sql varchar2(4000);
v_user varchar2(30);
v_sep varchar2(20);
v_cur SYS_REFCURSOR;
pur_rec purchase%ROWTYPE;
begin
for u in (SELECT * FROM ALL_TABLES WHERE OWNER LIKE 'BMP%' and table_name ='PURCHASE') loop
v_sql := v_sql || v_sep || 'SELECT * from '||u.owner||'.purchase';
v_sep := ' UNION ALL ';
end loop;
open v_cur for v_sql;
Loop
Fetch v_cur into pur_rec;
Exit when v_cur%NOTFOUND;
--DBMS_OUTPUT.PUT_LINE (PUR_REC.S_CODE||' '||Pur_rec.s_name);
End Loop;
close v_cur;
end;
END;Error Line
* open v_cur for v_sql;*
Error is :-
Encountered the symbol 'V_SQL' when expecting one of the following.
select
Encountered the symbol END when expecting one of the following.
Begin function package pragma procedure externalI changed my code ALSO Showing SAME error .
SQL> Declare
2 v_sql varchar2(4000);
3 v_user varchar2(30);
4 v_sep varchar2(20);
5 TYPE R_CURSOR IS REF CURSOR RETURN purchase%ROWTYPE;
6 C_Pur R_CURSOR;
7 ER C_pur%ROWTYPE;
8 BEGIN
9 for u in (SELECT * FROM ALL_TABLES WHERE OWNER LIKE 'BMP%' and table_name ='PURCHASE') loop
10 v_sql := v_sql || v_sep || 'SELECT * from '||u.owner||'.purchase';
11 v_sep := ' UNION ALL ';
12 end loop;
13 OPEN C_Pur FOR V_sql;
14 LOOP
15 FETCH C_Pur INTO ER;
16 EXIT WHEN C_Pur%NOTFOUND;
17
18 END LOOP;
19 CLOSE C_Pur;
20 END;
21 /
OPEN C_Pur FOR V_sql;
ERROR at line 13:
ORA-06550: line 13, column 7:
PLS-00455: cursor 'C_PUR' cannot be used in dynamic SQL OPEN statement
ORA-06550: line 13, column 2:
PL/SQL: Statement ignoredEdited by: Ahmed on Jan 13, 2011 1:58 AM -
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. -
Open cursor for PLSQL table of records
Is it possible to open a cursor for all data in a PLSQL table of records?
something like
cursor c (p1 number) is select * from <plsqltab>
where <plsqltab>.col = p1There is no such thing as a PL/SQL table. Yes, I know that many calls this structure in PL/SQL a table. And that is exactly where all this confusion stems from.. and trying to treat such a "table" as an Oracle table using SQL.
The correct terms are dynamic array (indexed by integer) or dynamic associative array (indexed by varchar). And an array is nothing like a table ito RDBMS processing.
Yes, you can run SQLs against arrays. But it is "expensive". Why? Because the data sits inside PL/SQL Engine. Not in the SQL Engine. The data is in a PL/SQL defined structure. Not a SQL defined structure.
So.. the data needs to be shipped from the PL/SQL Engine to the SQL Engine and converted into a format that the SQL Engine can understand and use.
Also, once shipped and converted the SQL structure is not indexed. Which means that the only option is a full table scan of that structure.
So you need to ask yourself why do you want to use SQL against a PL/SQL array? As soon as you do that, you are saying "Hey, this PL/SQL table ain't good enough and I need to process it using SQL".
So why then does that data sit inside a PL/SQL array and not in a SQL table?
Oracle provides you with the ability to create temporary session tables. These can be indexed. SQL can be run against them without all the "expenses" that are associated with running SQL against a PL/SQL array.
PL/SQL arrays is a great tool. But only when it is the right tool to use. When someone says he/she needs SQL to use this tool, then I question the choice of the tool. Make sure you use the right tool for the job. -
Delcare Cursor using Dynamic SQL using PL/SQL in Oracle 7.3.4
In Oracle 7.3.4, can I declare a cursor at run time using Dynamic SQL. From the sample code in this website, it seems that Oracle 8 support this function. Please help. Thanks a lot.
If I can do this on Oracle 7.3.4, could you give me some sample codes? Thanks.
Regards,
RaymondHi,
Try using the the following code where you can dynamically build the Valid Select stmt. and call that where ever you want.
declare
Type Cur_ref Is Ref Cursor;
C_ref Cur_ref;
V_Str Varchar2(100);
V_Name Varchar2(100);
Begin
V_Str := 'Select Ename from Scott.emp Where empno = 7369';
Open C_Ref for V_Str;
Fetch C_ref Into V_Name;
close C_Ref;
dbms_output.put_line(V_Name);
End;
regards
gaurav
null -
Dynamic fetch for dynamic sql query
Hi All,
I want to dynamically create a query and fetch it into a dynamic cursor record...The structure of the record should be the same as that of the query...
Can you suggest any method to do that.
eg
OPEN <dynamic cur> FOR <dynamic stmt>;
LOOP
FETCH <dynamic cur> INTO <dynamic rec>;
END LOOP;
CLOSE <dynamic cur>;
How do I declare the dynamic rec here?I would not know the columns in the query beforehand either.
Thanks,
Merz
Edited by: merz on Sep 12, 2011 5:02 PM
Edited by: merz on Sep 12, 2011 5:03 PMmerz wrote:
Hi All,
I want to dynamically create a query and fetch it into a dynamic cursor record...The structure of the record should be the same as that of the query...
Can you suggest any method to do that.And how are you expecting to write an application around a dynamic query and dynamic structure that you don't know?
Saying that, as others have said, there is the DBMS_SQL package which can be used for certain valid reasons such as the following example....
As sys user:
CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
/As myuser:
CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2
,p_dir IN VARCHAR2
,p_header_file IN VARCHAR2
,p_data_file IN VARCHAR2 := NULL) IS
v_finaltxt VARCHAR2(4000);
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_fh UTL_FILE.FILE_TYPE;
v_samefile BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file);
BEGIN
c := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
d := DBMS_SQL.EXECUTE(c);
DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
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);
WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
ELSE
DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
END CASE;
END LOOP;
-- This part outputs the HEADER
v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767);
FOR j in 1..col_cnt
LOOP
v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
END LOOP;
-- DBMS_OUTPUT.PUT_LINE(v_finaltxt);
UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
IF NOT v_samefile THEN
UTL_FILE.FCLOSE(v_fh);
END IF;
-- This part outputs the DATA
IF NOT v_samefile THEN
v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767);
END IF;
LOOP
v_ret := DBMS_SQL.FETCH_ROWS(c);
EXIT WHEN v_ret = 0;
v_finaltxt := NULL;
FOR j in 1..col_cnt
LOOP
CASE rec_tab(j).col_type
WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
ELSE
v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
END CASE;
END LOOP;
-- DBMS_OUTPUT.PUT_LINE(v_finaltxt);
UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
END LOOP;
UTL_FILE.FCLOSE(v_fh);
DBMS_SQL.CLOSE_CURSOR(c);
END;This allows for the header row and the data to be written to seperate files if required.
e.g.
SQL> exec run_query('select * from emp','TEST_DIR','output.txt');
PL/SQL procedure successfully completed.Output.txt file contains:
empno,ename,job,mgr,hiredate,sal,comm,deptno
7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10The procedure allows for the header and data to go to seperate files if required. Just specifying the "header" filename will put the header and data in the one file.
Adapt to output different datatypes and styles are required.
Maybe you are looking for
-
Apple Screwing Customers Who Bought Apple Software Pre-App Store
I bought iWork June 29, 2010. I had downloaded and installed the trial version of iWork and then paid for an activation key. Last month I bought a new mac book air. Because I downloaded iWork from Apple's website and then purchased and activation key
-
In full screen i have no picture of my TV. Screen is black. When it is not full screen i can watch the TV it is OK. Flash Player is good version.
-
How can I force iPhoto to store imported movies in a different folder?
I currently have 20GB of AVI video that have been imported over time from my digital camera. I would like to store the videos on a separate drive and still have iPhoto manage them. Is there a way to do this? Am I the only one with this problem?
-
By product showing only in recp reservation not in un resticted
Hii PP guru, when i enter by product in production order componenet.quantyty ; in -Ve and item category L and i tick on back flash.. when i confirm the order..by product showing in recp Reservation..but not showing in unrestricted. but when i do man
-
Pixelation in content viewer. Looks pixelated no matter what i try.
Hello there Everything looks pixelated in my slideshow when i look at it in content viewer. Images an especially text. The workarounds im been trying so far doesn't do the trick. So im thinking if im using af wrong viewer version? its version 32. If