Can a dynamic select stmt in a ref cursor be done?
Hello all!
I have a form in which a user can select a number of checkboxes that coorespond to fields in a table. After checking the desired boxes, the user can then click on a button and a variable (v_query) in a "when button pressed" trigger is populated with the text of a sql query. The trouble is, I want to incorporate the code contained in v_query into the REF cursor OPEN statement where it is expecting a sql query. The idea here is that the cursor would loop through the table fetching rows based on the select statement variable (v_query) and write them to a file using TEXT_IO(See below code). First, can this be done? Second, is there a better way to do accomplish this?
DECLARE
TYPE t_cur IS REF CURSOR ; -- define t_cur as a type
c_cur t_cur ; -- define an actual variable of type t_cur
r_emp emp%ROWTYPE ; -- PL/SQL record to hold row
v_query VARCHAR2(2000) := 'SELECT * FROM emp' ; -- the query!
BEGIN
-- OPEN FILE
out_file := Text_IO.Fopen('C:\BACHELOR\TEST.txt', 'w');
OPEN c_cur FOR v_query ; -- v_query could contain any valid query
LOOP
FETCH c_cur INTO r_emp ; -- get first row from dataset
EXIT WHEN %NOTFOUND
--PRINT TO FILE
Text_IO.Put_line(out_file, r_emp);
Text_IO.New_Line(out_file);
END LOOP;
CLOSE c_cur ; -- remember to close the cursor! ;)
END;
Hello all!
I have a form in which a user can select a number of checkboxes that coorespond to fields in a table. After checking the desired boxes, the user can then click on a button and a variable (v_query) in a "when button pressed" trigger is populated with the text of a sql query. The trouble is, I want to incorporate the code contained in v_query into the REF cursor OPEN statement where it is expecting a sql query. The idea here is that the cursor would loop through the table fetching rows based on the select statement variable (v_query) and write them to a file using TEXT_IO(See below code). First, can this be done? Second, is there a better way to do accomplish this?
DECLARE
TYPE t_cur IS REF CURSOR ; -- define t_cur as a type
c_cur t_cur ; -- define an actual variable of type t_cur
r_emp emp%ROWTYPE ; -- PL/SQL record to hold row
v_query VARCHAR2(2000) := 'SELECT * FROM emp' ; -- the query!
BEGIN
-- OPEN FILE
out_file := Text_IO.Fopen('C:\BACHELOR\TEST.txt', 'w');
OPEN c_cur FOR v_query ; -- v_query could contain any valid query
LOOP
FETCH c_cur INTO r_emp ; -- get first row from dataset
EXIT WHEN %NOTFOUND
--PRINT TO FILE
Text_IO.Put_line(out_file, r_emp);
Text_IO.New_Line(out_file);
END LOOP;
CLOSE c_cur ; -- remember to close the cursor! ;)
END;
Similar Messages
-
Select stmt offset - how can I use select stmt to fetch data.
kna1-name2 contains store#XXXXXXX where XXXXXXX is a store number. example : store#3564261.
I must fetch this. how can i fetch this ?
Can I use
WHERE substr(name2,7,10) CS gt_soldto1-store_no
or can I use
WHERE name2+7(10) CS gt_soldto1-store_no
along with for all entries IN gt_soldto1
in the below select stmt.
*SELECT *
FROM kna1
INTO corresponding fields of TABLE gt_kna1
FOR ALL ENTRIES IN gt_soldto1
WHERE substr(name2,7,10) as gt_soldto1-store_no
OR j_3astcu = gt_soldto1-store_no
THANKS IN ADVEasiest way would be to create another field in your table gt_soldto1 as NAME2.
update all entries in gt_SOLD2-NAME2 as cocatenation of 'store#' + gt_SOLD2-STORE_no
then use your select statment
SELECT *
FROM kna1
INTO corresponding fields of TABLE gt_kna1
FOR ALL ENTRIES IN gt_soldto1
WHERE NAME2 = gt_soldto1-name2 -
How can i dynamically select columns based on the input parameter?
I have an input parameter which takes single numeric value.
Based on this value i have to dynamically select table-columns .
For eg: if i have following fields in my table :
SEM_1
SEM_2
SEM_3 and SEM_4.
And if i give numeric input as 2 , then i have to select "SEM_2" column only.
if the input is 3 then i have to select "SEM_3" only and leave the rest of the columns.
how do i achieve this dynamic feature in the "Select ..... From...... table...." statement in the ABAP??Hi,
you should try something like this.
TYPES: cond(72) TYPE c.
data: condtab TYPE TABLE OF cond,
condw type cond.
data: lv_field(30) type c value 'SEM_'.
write p_num to lv_field+4(1).
condw = lv_field.
append condw to condtab.
SELECT (CONDTAB) FROM table INTO.....
Kostas
Message was edited by:
Kostas Tsioubris -
Create record variable that refers dynamic query assigned to a ref cursor?
Hi ,
Just explaining what I am trying to achieve:
1) i have a hr.departments table that was loaded in hr schema on 1st oct 2012 with 4 columns(department_id, department_name, manager_id, location_id)
2) now I have a new schema by my name 'rahul' and I have loaded departments table but now an additional column has come into picture,ie created_date, this table got loaded on 1st-Nov-2012
3) Now going forward my columns could be dropped from the departments table (it can be a case), for example might be my departments table in my schema 'rahul' one day could comprise of only 3 columns(department_id,department_name,manager_id)
4) Now in the next step, I have managed to extract common column names(in a single line where columns are delimited using a comma) from both the tables(hr.departments and rahul.departments) which are (department_id, department_name, manager_id, location_id) using all_tab_cols table and I have written a function for it which i will be pasting below.
5) now going forward, using the above column names line with column names delimited using comma, I have used a ref cursor and assigned a query to it using the line of columns that I have extracted from the above point
6) Now I want to create a record variable which refers to my ref cursor, something like we do when we create a record variable by reffering to an explicit cursor defination that we give in the declaration block.
PS:
1) I have been out of touch with plsql for a long time so I have lost a lot of mmeory regarding plsql.
2) basically I need to compare data in hr.departments table with rahul.departments table for only columns that are common to both the tables, rest new or discarded columns information will go in one of the log tables that I have created(this is done already)
Please help me, I did try searching on google for the same but it really confused me very badly, any kind of help is appreciated, please find my code below:
Regards
Rahul
Code :
===================================================================================================
create or replace procedure p_compare_data(fp_old_table_name in varchar2, fp_new_table_name in varchar2)
is
type ref_cursor_old_table is ref cursor;
v_ref_cursor_old_table ref_cursor_old_table;
--record_v_ref_cursor_old_table v_ref_cursor_old_table;
--record_ref_cursor_old_table v_ref_cursor_old_table%ROWTYPE;
Lv_all_column_names varchar2(2000);
function f_fetch_common_column_names(fp_old_table_name in varchar2, fp_new_table_name in varchar2)
return varchar2
is
Lv_all_column_names varchar2(2000);
begin
execute immediate 'select ltrim(all_column_names,'','') all_column_names_in_line from (select * from (select sys_connect_by_path(hr_e_column_name,'','') all_column_names from (select hr_e_column_name, rownum curr, rownum - 1 prev from (select hr_e.* , rahul_e.* , case when (hr_e_column_name = rahul_e_column_name) then 1 when (rahul_e_column_name is NULL) then 2 when (hr_e_column_name is NULL) then 3 end decision from (select column_name hr_e_column_name from all_tab_cols where owner ='''||substr(fp_old_table_name,1,instr(fp_old_table_name,'.',1,1)-1)||''' and table_name = '''||substr(fp_old_table_name,instr(fp_old_table_name,'.',1,1)+1)||''') hr_e full outer join (select column_name rahul_e_column_name from all_tab_cols where owner = '''||substr(fp_new_table_name,1,instr(fp_new_table_name,'.',1,1)-1)||''' and table_name = '''||substr(fp_new_table_name,instr(fp_new_table_name,'.',1,1)+1)||''') rahul_e on hr_e.hr_e_column_name = rahul_e.rahul_e_column_name) decision_table where decision = 1) a start with a.curr = 1 connect by prior curr = prev) b order by length(b.all_column_names) desc) all_column_names_in_line where rownum = 1' into Lv_all_column_names;
return (Lv_all_column_names);
end;
begin
Lv_all_column_names := f_fetch_common_column_names(fp_old_table_name, fp_new_table_name);
--dbms_output.put_line(Lv_all_column_names);
open v_ref_cursor_old_table for ('select '||Lv_all_column_names||' from '||fp_old_table_name);
end;
=====================================================================================================>
6) Now I want to create a record variable which refers to my ref cursor, something like we do when we create a record variable by reffering to an explicit cursor defination that we give in the declaration block.
>
This thread is basically nothing more than a continuation of your original thread except now you are finally explaining what you are really trying to do.
Re: passing table name to a procedure and then need to open a cursor ..
In that original thread you said you found the solution
>
Well Mate thanks for your suggestion but I got it working through ref cusror, thanks for your time.
>
So I ask you to post your 'solution' and when you finally did it was clear that you hadn't solved anything at all. Your solution used a ref cursor all right but the code relied on a record ('record_employees') that was based on a table name ('employees') that was declared within the procedure. There isn't much point in passing in a table name if you have to hard-code the table name in the procedure.
create or replace procedure p_ref_cursor(fp_old_table in varchar2)
is
type ref_cursor is REF CURSOR;
v_ref_cursor ref_cursor;
record_employees hr.employees%ROWTYPE;
begin
open v_ref_cursor for 'select * from '||fp_old_table;
loop
fetch v_ref_cursor into record_employees;
exit when v_ref_cursor%NOTFOUND;
dbms_output.put_line(record_employees.employee_id);
end loop;
end;Then sb92075 ask you the question that illustrates what I just said
>
what happens when you pass in "HR.DEPARTMENTS" ; besides throwing errors?
>
And you blew him off with this
>
Mate, departments never came in my context, in my prior message I explained what I was trying to achieve ... so I dont know what problem you are understanding reading my posts.
>
And now here you are asking how to get this to work for the departments table.
It is very difficult to help someone that won't tell us what it is they are really trying to do so we can try to suggest some better ways of doing it. Hopefully, in the future, you wil start by explaining your problems instead of focusing on the solution you think you should use.
Back to the issue -
The first thing you should do is finish defining the requirements. Assuming the above actually works to identify columns that have different data what are you going to do with that information?
1. Do you need to save that different data from TABLE1 somewhere?
2. If you don't save it how will anyone look at it to decide which table has the correct data?
3. If you do save it how will you save it 'generically' since other tables will have different columns and datatypes?
4. What about the data from the same record in TABLE2; do you need to save that data somewhere?
5. Will these two tables have primary keys? Are they on the same columns in each table? If not what if TABLE1 has one record but there are TWO records in TABLE2 that are identical. Is that a match? Or is that a problem because TABLE2 has an extra record even though the record is identical?
In short detecting the differences is just one small part of the entire problem. You also need to save those differences somewhere so someone can examine the data and decide what action to take. That is the more difficult part of trying to implement a 'generic' solution.
But now that we know what you are really trying to do take a read through this thread from 6 years ago. It has three different ways to pass a query to a procedure and get different output. You may want to save a copy of the thread since it has some very advanced techniques in it.
How to pipeline a function with a dynamic number of columns?
See ascheffer's reply Posted: May 9, 2006 4:53 AM for using data cartridge functionality with a pipelined function.
See Kamal's reply Posted: May 10, 2006 4:49 AM - it shows how to get XML output.
See BluShadow's reply Posted: Mar 27, 2009 1:50 AM - for using dynamic sql -
An issue with Dynamic SQL within Package using REF CURSOR
Hi there,
In the following package first two procedures works file but since I have added the third one ( GET_CONTRACT_BY_DYN_SQL) it does not work for me. When I try to compile and save it gives below error.
"Error(6,15): PLS-00323: subprogram or cursor 'GET_CONTRACT_BY_DYN_SQL' is declared in a package specification and must be defined in the package body"
Can you please help?
Package Header
create or replace
PACKAGE CONTRACTS_PKG AS
TYPE T_CURSOR IS REF CURSOR;
PROCEDURE GET_CONRACTS (IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_ID (I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRATID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR);
END CONTRACTS_PKG;
Package Body
create or replace
PACKAGE BODY CONTRACTS_PKG AS
-- Get All Contracts
PROCEDURE GET_CONRACTS(IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS;
IO_CURSOR := V_CURSOR;
END GET_CONRACTS;
-- Get Contract By ID
PROCEDURE GET_CONTRACT_BY_ID(I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS WHERE contract_id = I_CONTRACTID;
IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_ID;
-- Get Contract Using Dynamic SQL
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
V_SQL VARCHAR2(200);
BEGIN
V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS WHERE contract_id = ' || P_CONTRACTID ;
--OPEN V_CURSOR FOR
--EXECUTE IMMEDIATE V_SQL INTO V_CURSOR;
OPEN V_CURSOR FOR V_SQL;
EXECUTE IMMEDIATE V_SQL;
--IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_DYN_SQL;
END CONTRACTS_PKG;
Thanks in advance.
HiteshThanks guys. Finally I have tweaked as per your suggestions and it's working for all 3 cases (stored procedures).
Oracle
======
Package Header
create or replace
PACKAGE CONTRACTS_PKG AS
TYPE T_CURSOR IS REF CURSOR;
PROCEDURE GET_CONRACTS (IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_ID (I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR);
END CONTRACTS_PKG;
Package Body
create or replace
PACKAGE BODY CONTRACTS_PKG AS
-- Get All Contracts
PROCEDURE GET_CONRACTS(IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS;
IO_CURSOR := V_CURSOR;
END GET_CONRACTS;
-- Get Contract By ID
PROCEDURE GET_CONTRACT_BY_ID(I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS WHERE contract_id = I_CONTRACTID;
IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_ID;
-- Get Contract Using Dynamic SQL
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
V_SQL VARCHAR2(200);
BEGIN
IF p_contractid > 0 THEN
V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS WHERE contract_id = ' || P_CONTRACTID ;
ELSE
V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS';
END IF;
OPEN V_CURSOR FOR V_SQL;
IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_DYN_SQL;
END CONTRACTS_PKG;
ColdFusion (calling app code)
=====================
<cfstoredproc procedure="CONTRACTS_PKG.GET_CONTRACT_BY_ID" datasource="#REQUEST.dsn#">
<cfprocparam cfsqltype="CF_SQL_INTEGER" type="in" value="1" variable="I_CONTRACTID">
<cfprocresult name="qData" resultset="1">
</cfstoredproc>
<br>Single Contract:
<cfdump var="#qData#" label="Single Contract">
<cfstoredproc procedure="CONTRACTS_PKG.GET_CONRACTS" datasource="#REQUEST.dsn#">
<cfprocresult name="qDataAll" resultset="1">
</cfstoredproc>
<br>All Contracts:
<cfdump var="#qDataAll#" label="All Contracts">
<cfstoredproc procedure="CONTRACTS_PKG.GET_CONTRACT_BY_DYN_SQL" datasource="#REQUEST.dsn#">
<cfprocparam cfsqltype="CF_SQL_INTEGER" type="in" value="1" variable="P_CONTRACTID">
<cfprocparam cfsqltype="CF_SQL_VARCHAR" type="in" value="contract_number,contract_title,created_date" variable="P_COLS">
<cfprocresult name="qDataDynSQL" resultset="1">
</cfstoredproc>
<br>Dynamic SQL Query:
<cfdump var="#qDataDynSQL#" label="Dynamic SQL Query">
Thanks,
Hitesh Patel -
How can I see the contents in a Ref Cursor
I have this code:
CREATE OR REPLACE PACKAGE APOD_LOG.APOD_C3_LOG_API_PKG
AUTHID CURRENT_USER
AS
type rc is ref cursor;
PROCEDURE Fetch_Log_Spec
in_LOCAL_IP_VALUE IN BINARY_INTEGER,
out_RESULT_SET OUT rc
END APOD_C3_LOG_API_PKG;
CREATE OR REPLACE PACKAGE BODY APOD_LOG.APOD_C3_LOG_API_PKG
AS
PROCEDURE Fetch_Log_Spec
in_LOCAL_IP_VALUE IN BINARY_INTEGER,
out_RESULT_SET OUT rc
IS
BEGIN
DBMS_APPLICATION_INFO.set_module(module_name => 'APOD_LOG.API_PKG',action_name => 'Fetch_Log_Spec');
DBMS_APPLICATION_INFO.set_client_info(client_info => 'Calling with in_LOCAL_IP_VALUE = ' ||to_char(in_LOCAL_IP_VALUE));
open out_RESULT_SET for
select
in_LOCAL_IP_VALUE as IN_LOCAL_IP_VALUE,
10002 as PORT,
APOD_CORE.UTIL_IP_PKG.IPAddressToIPValue2('''224.168.100.1''') as MULTICAST_IP_VALUE
from
dual
union
select
in_LOCAL_IP_VALUE as IN_LOCAL_IP_VALUE,
10002 as PORT,
APOD_CORE.UTIL_IP_PKG.IPAddressToIPValue2('''224.168.200.1''') as MULTICAST_IP_VALUE
from
dual
union
select
in_LOCAL_IP_VALUE as IN_LOCAL_IP_VALUE,
10002 as PORT,
APOD_CORE.UTIL_IP_PKG.IPAddressToIPValue2('''224.168.100.123''') as MULTICAST_IP_VALUE
from
dual
union
select
in_LOCAL_IP_VALUE as IN_LOCAL_IP_VALUE,
10002 as PORT,
APOD_CORE.UTIL_IP_PKG.IPAddressToIPValue2('''224.168.200.123''') as MULTICAST_IP_VALUE
from
dual;
DBMS_APPLICATION_INFO.set_client_info(client_info => 'Called Fetch_Log_Spec '||to_char(SQL%ROWCOUNT)||' row(s) returned with in_LOCAL_IP_VALUE = '||to_char(in_LOCAL_IP_VALUE) );
END Fetch_Log_Spec;
END APOD_C3_LOG_API_PKG;
And I am trying to test it like this:
DECLARE
IN_LOCAL_IP_VALUE BINARY_INTEGER;
OUT_RESULT_SET APOD_LOG.APOD_C3_LOG_API_PKG.rc;
BEGIN
IN_LOCAL_IP_VALUE := 23374048;
-- OUT_RESULT_SET := NULL; How do I see this
APOD_LOG.APOD_C3_LOG_API_PKG.FETCH_LOG_SPEC ( IN_LOCAL_IP_VALUE, OUT_RESULT_SET );
END;
How can I see the dataset returnd by the OUT_RESULT_SET in SQLPlus or Quest ScriptRunner?A ref cursor doesn't really contain rows but you can use them to reference a SQL statement that fetches the rows.
Re: returning resultset from procedure...or pkg -
Multiple SELECTS returned to a REF CURSOR
Hi there
I have a query regarding returning a REF Cursor from multiple selects and any input/hints would be greatly appreciated.
Basically, I have a select(from multiple tables) that returns a set of rows(query 1) and another (from multiple tables) that returns a set of data that needs to be appended to the results from query 1. Initially my thoughts were to join the queries using an inline view. This returns the correct number of rows but as there is only 1 field I can use to join the queries it is very inefficient and takes forever to execute.
So, I’ve there for had to rethink my design but have hit a brick wall – so to speak!
Is it possible to use one cursor for each query and return the results in 1 ref cursor?
I’m thinking I would need something like the following: -
Cursor 1 is
Select a.quote, b.name,c.price from table a,b,c
Cursor 2 (cursor 1.quote IN)
Is
Select * from table d,e,f
Where d.quote = cursor1.quote
What I need to output in the ref cursor is as follows: -
For each record returned from query 1, return the data from query 2.
Many thanks in advance
ps I'm using 9iDo UNION or UNION ALL work on your version of Oracle? <g>
-
Can I dynamically select the FTP account and destination?
I have a situation where, dependent, on a field in the contents of a CSV file I need to FTP it to a certain location.
Now there are over 40 cases and I'd rather not set up 40 outbound FTP services, each with their own account but would rather have just one and dynamically set the account information from a configuration available from within the pipeline (i.e. via some user defined properties).
Is there a way of doing this?
regardsI've made some progress on this. The XQuery function:
fn-bea:lookupBasicCredentials
can be used to get service account information at run time so now all I need is to be able to override some header values so that the FTP transport uses them instead but also need a means to change the FTP URL.
Surely someone has come across this problem before and solved it? -
Can we dynamically select DataSets in Data Model of a BI Publisher Report?
Hello,
I have a requirement as below -
For a report 'XX Report1' we have Data Model(concatenated SQL Data Source) with 3 Datasets -
New DataSet1 - WebService Call (WSDL) (Say D1)
New DataSet2 - SQL QueryA (Say D2)
New DataSet3 - SQL QueryB (Say D3)
Layout - 'XXRTFFile.RTF'
And another report 'XX Report2' with Data Model(concatenated SQL Data Source) with 3 Datasets -
New DataSet1 - SQL QueryC (Say D4)
New DataSet2 - SQL QueryA (D2)
New DataSet3 - SQL QueryB (D3)
Layout - 'XXRTFFile.RTF'
Note that DataSet2 and DataSet3 have the same queries in both the reports.
'XX Report1' is called from Siebel frontend through a URL
'XX Report2' is called from Batch Programming later.
The requirement is to come up with a single Report for both of these calls.
So, I thought of merging all the DataSets in to 1 Data Model as D1,D2,D3,D4.
Is there a way for us to select the DataSets from Data Model using the Parameters when Report is run, so that the report picks up D1, D2, D3 if it is called from Siebel frontend and D4,D2,D3 if its run from Batch Programming?
Please let me know.Thanks in advance.
Thanks,
PhaniThe web services API would probably be your best bet. http://download.oracle.com/docs/cd/E10415_01/doc/bi.1013/e10416/bip_webservice_101331.htm#CHDGIJHH
There is some Java examples in the above. I'm guessing the c# code wouldn't be too different.
Bryan -
Alternative to native, dynamic sql to return a ref cursor to a client
I'm on Oracle 8.0.4, and would like to pass a string of values like '1,2,7,100,104' that are the primary key for a table. Then use something like:
procedure foo( MyCur RefCurType, vKey varchar2)
begin
open MyCur for
'select names from SomeTable' | |
' where ID in (' | | vKey | | ')'
end;
This would return a recordset to (in this case) a Crystal Reports report.
However, native dynamic SQL ain't available until 8.1.0. So can anyone think of a clever way to accomplish this, with a way to return a cursor? I can't figure out how to do this with DBMS_SQL, because open_cursor is just returning a handle, not a referene to a cursor that can be passed to a remote client.
Thanks in advance.I'm on Oracle 8.0.4, and would like to pass a string of values like '1,2,7,100,104' that are the primary key for a table. Then use something like:
procedure foo( MyCur RefCurType, vKey varchar2)
begin
open MyCur for
'select names from SomeTable' | |
' where ID in (' | | vKey | | ')'
end;
This would return a recordset to (in this case) a Crystal Reports report.
However, native dynamic SQL ain't available until 8.1.0. So can anyone think of a clever way to accomplish this, with a way to return a cursor? I can't figure out how to do this with DBMS_SQL, because open_cursor is just returning a handle, not a referene to a cursor that can be passed to a remote client.
Thanks in advance. -
How we can pass the list of variable from ref cursor ??
pls explain with example
Simple example:
SQL> create table t as select level col from dual connect by level <= 10;
Table created.
SQL> create or replace procedure myproc
2 ( p_num_list in sys.odcinumberlist
3 , p_ref out sys_refcursor
4 )
5 as
6 begin
7 open p_ref for select col
8 from t
9 where col in (select * from table(p_num_list));
10 end;
11 /
Procedure created.
SQL> var rc refcursor
SQL> set autoprint on
SQL> exec myproc(sys.odcinumberlist(1,2,3), :rc);
PL/SQL procedure successfully completed.
COL
1
2
3
3 rows selected.
SQL> exec myproc(sys.odcinumberlist(1), :rc);
PL/SQL procedure successfully completed.
COL
1
1 row selected.
Search http://asktom.oracle.com for more examples...
Also, see:
The Tom Kyte Blog: Varying in lists... -
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 All,
I have a requirement that i need to execute query having dynamic number of columns using Ref Cursor e.g.
v_string := 'PO_NUMBER , ORG_ID' ;
v_query := 'SELECT '|| v_string || 'FROM table_name';
Can someone please quide me how to define Type dynamically for the above requirement ?
Thanks
Vipul Maheshwarihope you understand how to use this with the help of ref cursor
CURSOR Expressions
A CURSORexpression returns a nested cursor. This form of expression is equivalent to
the PL/SQL REF CURSORand can be passed as a REF CURSORargument to a function.
A nested cursor is implicitly opened when the cursor expression is evaluated. For
example, if the cursor expression appears in a select list, a nested cursor will be
opened for each row fetched by the query. The nested cursor is closed only when:
■ The nested cursor is explicitly closed by the user
■ The parent cursor is reexecuted
■ The parent cursor is closed
■ The parent cursor is cancelled
■ An error arises during fetch on one of its parent cursors (it is closed as part of the
clean-up)
Restrictions on CURSOR Expressions The following restrictions apply to CURSOR
expressions:
■ If the enclosing statement is not a SELECTstatement, then nested cursors can
appear only as REF CURSORarguments of a procedure.
■ If the enclosing statement is a SELECTstatement, then nested cursors can also
appear in the outermost select list of the query specification or in the outermost
select list of another nested cursor.
■ Nested cursors cannot appear in views.
■ You cannot perform BINDand EXECUTEoperations on nested cursors.
Examples The following example shows the use of a CURSORexpression in the
select list of a query:
SELECT department_name, CURSOR(SELECT salary, commission_pct
FROM employees e
WHERE e.department_id = d.department_id)
FROM departments d
ORDER BY department_name;
The next example shows the use of a CURSORexpression as a function argument. The
example begins by creating a function in the sample OEschema that can accept the
REF CURSORargument. (The PL/SQL function body is shown in italics.)
CREATE FUNCTION f(cur SYS_REFCURSOR, mgr_hiredate DATE)
RETURN NUMBER IS
emp_hiredate DATE;
before number :=0;
after number:=0;
begin
loop
fetch cur into emp_hiredate;
exit when cur%NOTFOUND;
if emp_hiredate > mgr_hiredate then
after:=after+1;
else
before:=before+1;
end if;
end loop;
close cur;
if before > after then
return 1;
else
return 0;
end if;
end;
The function accepts a cursor and a date. The function expects the cursor to be a query
returning a set of dates. The following query uses the function to find those managers
in the sample employeestable, most of whose employees were hired before the
manager.
SELECT e1.last_name FROM employees e1
WHERE f(
CURSOR(SELECT e2.hire_date FROM employees e2
WHERE e1.employee_id = e2.manager_id),
e1.hire_date) = 1
ORDER BY last_name; -
Dynamic Selection in S_ALR_87012079
Hi,
The dynamic selection in the report S_ALR_87012079 does not seem to be working..If I enter a document type in dynamic selection, even then it displays all document type in the output and does not give me output for that document type only..
Has anyone faced this or is there any SAP note on this..?
Regards,
SAPFICOHi,
While I was searching for SAP note on this, I did find some OSS notes where dynamic selections were not working and SAP had given some code corrections for S_ALR reports but not this one..
Any idea whether we can get dynamic selection work for this report?
Regards,
SAPFICO -
Read Dynamic Selection contents of a Variant for QE51N
Hi Folks,
Need your help here !
In my report, I wish to read the Variants along with their contents created for transaction QE51N.
I tried using function module RS_VARIANT_CONTENTS and its working good, but not to my requirements. The function module returns only the selection screen contents of a given variant. It does not return the contents in 'Dynamic Selection' (Free Selection).
I read somewhere that the function module returns dynamic selection contents only if the report use Logical Database. To my understanding, the program for QE51N (SAPLQEES) do not use LDB.
So is there any way by which I can get dynamic selection contents of a variant?
Any suggestions / pointers would be a great help.
Thank you.
Regards,
Sud.Hi,
Did you find somethings? I have the same issue.
I would like to add some new fields on Dynamic Selection screen of QE51N.
Thanks in advance.
KR,
Arnaud
Maybe you are looking for
-
Mac Air Security, Internet Issues: System Report Attached
I don't know if it's my fault that my brand new Macbook Air is having so many problems. I am not in the know with the terms so I have attached a system report. Basically unable to keep users off of my internet network (private supposedly), On both my
-
How do i apply a password to my guest network
How do I apply a password to the guest network. I can't remember how I created the guest network in the first place
-
I just upgraded to 10.4.4 and I am having trouble bacing up and copying .aiff files. I get error messages stating that the file does not exist or the file name id too long. This happens intermitently when I try to back up to external fire wire drives
-
Do you have to make an appointment to have a repair on the iPod fixed ?
MY iPod Screen is cracked and I was wondering if I had to make an appointment with the Apple Store. Like, is it absolutely necessary ?
-
Depreciation run: Needs restart but asset shows posted while GL not posted.
Hi, An asset was set up in the wrong asset class. The asset class is not fully configured. Depreciation ran in real mode and error as the accumulated depreication account is wrong and cannot be used. It says it must be RESTARTED. However, the asset v