Dynamic cursor definition in PL/SQL
Is it possible to have dynamic cursor definition in PL/SQL. Like
using DBMS_SQL for dynamic SQL. If yes, how?
Assuming I understand your question correctly, you can use a REF
CURSOR to which you associate a VARCHAR2 which is the query text:
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 c_cur FOR v_query ; -- v_query could contain any valid query
FETCH c_cur INTO r_emp ; -- get first row from dataset
CLOSE c_cur ; -- remember to close the cursor! ;)
END ;
HTH
Similar Messages
-
Variable in the Cursor definition?
Shall we provide a variable in the cursor definition.? Like this,
CREATE OR REPLACE PROCEDURE PRC_PROCEURE1 (v_table in varchar2) IS
CURSOR C1 IS select COL1,COL2,COL3 from V_TABLE
where ......
order by 1 asc
Getting the error :table or view does not exists. Please helpYou can only bind values into your queries, not object names, so NO, you can't use a variable as a table name like that.
The only way to do that would be to write dynamic SQL, but that should raise the question as to why you need dynamic table names? Do you not know the table name at design time? Why not? -
Semi-dynamic cursor on heterogeneous tables
I have a list of Microsoft Access databases. They are yearly transaction databases. The tables in each look exactly alike.
What I need to do is loop through the "list of databases" (which I retrieve from a secondary source), and loop through table T1 in each of these databases. I could use the completely-dynamic code at AskTom, but I'm guessing that's going to have horrible performance. In my case,I know what the columns are. The only thing that's changing is the link to the database itself. So here's what I want to do:
Declare a generic cursor C1 (but without linking to any particular database's rowtype).
Loop through all database link names:
set C1 = 'select * from T1@' || linked_db_name;
for rec_c1 in C1 loop
dbms_output.put_line(rec_c1.field1);
dbms_output.put_line(rec_c1.field2);
end loop;
end loop;
Is there a way to do this, where I can refer to each field by name? Or must I use the describe and/or have a non-generic cursor as the basis for the cursor definition? My backup option is to drop and recreate the database link each time, with a "reference" DB link created at the outset by the customer. But I don't know if I can do that in PL/SQL (drop and recreate database links).
Thanks for your assistance!
Christine Wolak
SPL Worldgroup, IncChristine:
I've never actually tried this across a db_link to Access, but it should work.
DECLARE
l_sql VARCHAR2(4000);
l_cur SYS_REFCURSOR;
TYPE access_rec IS RECORD (col1 VARCHAR2(35),
col2 VARCHAR2(35));
-- Whatever the appropriate Oracle data type is for the Access field
-- To do just singleton selects
l_ar access_rec;
-- To do bulk collect
TYPE access_tbl IS TABLE of access_rec INDEX BY BINARY_INTEGER;
l_at access_tbl;
BEGIN
FOR dbs in (SELECT link_name FROM db_table) LOOP
l_sql := 'SELECT * FROM t1@'||dbs.link_name;
OPEN l_cur FOR l_sql
-- For singleton selects
LOOP
FETCH l_cur INTO l_ar
EXIT WHEN l_cur%NOTFOUND;
<< Do whatever here using l_ar.col1, l_ar.col2>>
END LOOP;
-- For bulk collects
LOOP
FETCH l_cur BULK COLLECT INTO l_at LIMIT 100
-- Limit not strictly neccessary, but if ther are a large
-- number of rows it might be wise.
FOR i IN 1 .. l_at.COUNT LOOP
<< Do whatever here using l_at(i).col1, l_at(i).col2>>
END LOOP;
EXIT WHEN l_cur%NOTFOUND;
-- Note that the last fetch may retrieve less than LIMIT rows.
-- it will set NOTFOUND true, so you need to test at the end
-- of the loop
END LOOP;
CLOSE l_cur;
END LOOP;
END;HTH
John -
Hi,
I am using 10g and wanted to check if we can use a dynamic cursor in a procedure.
Following is my code and wanted to see if that can work with every query passed as a parameter.
example ,
exec test1 ('select col1, col2, col3 from table1','Two columns Sql')
exec test1 ('select col1 from table2','one columns Sql')
exec test1 ('select col1, col2, col3, col4, col5 from table3','Five columns Sql')
CREATE OR REPLACE procedure test1 (p_sql IN VARCHAR2, p_subject IN VARCHAR2
is
v_cu_string VARCHAR2(2000);
v_string VARCHAR2(2000);
v_sql VARCHAR2(4000);
v_head VARCHAR2(4000);
v_head_sql VARCHAR2(4000);
v_str_sql VARCHAR2(4000);
TYPE cv_typ IS REF CURSOR;
cv cv_typ;
begin
v_sql := p_sql;
OPEN cv FOR v_sql;
LOOP
FETCH cv INTO v_cu_string;
EXIT WHEN cv%NOTFOUND;
------ Processing steps
END LOOP;
CLOSE cv;
END;Thanksuser527060 wrote:
Following is my code and wanted to see if that can work with every query passed as a parameter.
Just curious as to why this is an improvement of
exec test1 ('select col1, col2, col3 from table1','Two columns Sql')
select col1, col2, col3 from table1And
exec test1 ('select col1 from table2','one columns Sql')
select col1 from table2And
exec test1 ('select col1, col2, col3, col4, col5 from table3','Five columns Sql')
select col1, col2, col3, col4, col5 from table3It needs more code from you to build, more code for anyone to enter to execute, limits selects to only one table I would guess also comes with less documentation than SQL.
http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/toc.htm -
Does Declare Dynamic Cursor Support with Order Clause?
Given a dynamic cursor like
declare CUR_10 dynamic cursor for SQLSA;
prepare SQLSA from :ls_SQL;
open dynamic CUR_10;
do while TRUE
fetch CUR_10 into :ls_var1, :ls_var2
loop
where ls_SQL is "select COL1, COL2 from TABLE_A order by COL2 desc"
can I fetch values in the exact DESCENDING order of COL2?Hello Ronald,
Values will be fetched in the way you SQL statement has been defined for your dynamic cursor, so in the descending order.
I've tested your code with an Oracle connection and it works perfectly.
Just ensure to add a condition to your DO WHILE statement when the resultset is exhausted:
DO WHILE TRUE AND SQLCA.SQLCode <> 100
Kind regards,
Jacob -
hi forum
I need your help and I hope you can help me. In my job I need to do a Report, but the function that containts the cursor returns a ref cursor and this ref cursor doesn't return a special format 'cause the cursor that I use is Dynamic so when I try to do the report it is not generated.
the documentation says that should return something for example
type vref_cursor is ref cursor[b] return record;
or
type vref_cursor is ref cursor return depto%rowtype;
but if I use this in a dynamic cursor it generates an Error and don't accpet this declaration only the following
type vref_cursor is ref cursor;
Do you Know how should I do the report with a dynamic cursor ?
best regards
thank's a lotThat is not possible. From the online help:
Each ref cursor query is associated with a PL/SQL function that returns a strongly typed ref cursor. -
Fetching values of Dynamic Cursor
Hi,
Can I fetch values of dynamic cursor into a variable(record OR individual)? If yes what will be the type of that record/variable?
Thanks in Advance!
Regards
RKbluefrog wrote:
There is no way in 10g to identify the column data types of the result set of a dynamic ref cursor.
In 11g one can use ;
DBMS_SQL.DESCRIBE_COLUMNS (
c IN INTEGER,
col_cnt OUT INTEGER,
desc_t OUT DESC_TAB);when using DBMS_SQL
P;In 11g you can use a ref cursor and then use the DBMS_SQL package to convert that ref cursor to a DBMS_SQL cursor where you can then describe the columns. The initial query doesn't have to be a DBMS_SQL cursor. In 10g, unfortunately, there is no way to convert the ref cursor to a DBMS_SQL cursor, so dynamic cursors would have to be written as DBMS_SQL cursors initially. Ref cursors are only really suitable for 3rd party tools, such as when passing queries back to .NET or Java applications. Too many people try and use ref cursors inside PL/SQL and then discover why that's not a good idea.
PL/SQL 101 : Understanding Ref Cursors:-
PL/SQL 101 : Understanding Ref Cursors -
Can I create a dynamic cursor in a program unit on oracle form....
Hello folks,
can I create a dynamic cursor on client side ( in a program unit on the oracle form), is it possible, I Know how to create it on server side using Ref cursor, but on client side i got this message (can't be created on client side or something like that).... please if someone can help> select count(*) from t_comsis
<p>But when you put that select string into a varchar2 variable, it won't compile. Which makes it hard to create anything "dynamic".
<p>In Forms, you can create and populate a record group dynamically, which is ok as long as your select will not retrieve too many (more than several hundred) rows.
<p>Or, your other option is to use the Forms Exec_SQL dynamic sql package. -
How do I show multiple rollover images on a page inserted dynamically (pulled out of a sql database table) using Dreamweaver’s Repeat Region. Example: I have different products each one associated (through their productID) with two images (one that’s showing in the page and one for the rollover effect) that are pulled from a database using Dreamweaver’s Recordset. So I want to end up with a page containing row after row of images(one for every product).When moused over each image will reveal the second (rollover) image for the same product which in turn can be a link(the image itself ) that when clicked leads to a detailed page with more information about the product the image is associated with. To show row after row with images for the different products in the database table I am using Dreamweaver’s Insert Rollover Image command and then the Repeat Region – I have no problem to complete the steps, to insert the image and the rollover one at once and set the paths so they are pulled dynamically depending on the productID they are associated with .I have also no problem to apply the Repeat Region so not only the first image associated with the first product in the table is shown but all of them-a routine and standard procedure when using the Repeat Region to dynamically generate and display multiple rows of data. However, when I preview the page the rollover effect is lost –the images are shown but when moused over the second image does not show. The problem is caused when the Repeat Region is applied-once again I am allowed to apply it but the rollover stops working, a kind of interference. ANY SOLLUTION PLEASE, ANY WORK AROUND.
I gotta tell you, using multiple images for rollover effects is going to be a big challenge in your dynamic scenario.
If this were my product page, I would use thumbnails with a bit of CSS opacity or filters to desaturate and make them full opacity/color on mouse over. Nice effect with much less bandwidth. Easily done globally with CSS code.
Two examples:
http://alt-web.com/GALLERY/GalleryTest.php
http://alt-web.com/TEMPLATES/CSS-Semi-liq-photo-sheet.shtml
Nancy O. -
Dynamic table name in native SQL
Hi,
How can i use dynamic table name in native SQL?
My req is to select data from a external database table , but the table name will be only poulated during runtime.
How can i acheive this?
Regards,
Arun.It should work OK - see demo below.
Jonathan
report zsdn_jc_adbc_test.
start-of-selection.
perform demo_lookup.
form demo_lookup.
data:
l_error_msg type string,
ls_t001 type t001, "Company
ls_t003 type t003. "Doc types
perform dynamic_lookup
using
'T001'
changing
ls_t001
l_error_msg.
write: / l_error_msg.
perform dynamic_lookup
using
'T003'
changing
ls_t003
l_error_msg.
write: / l_error_msg.
endform.
form dynamic_lookup
using
i_tabname type tabname
changing
os_data type any
o_error_msg type string.
* Use ADBC to select data
data:
l_mandt_ref type ref to data,
l_result_ref type ref to data,
l_mandt type symandt,
l_tabname type tabname,
l_sql_statement type string,
lo_cx_root type ref to cx_root,
lo_cx_sql type ref to cx_sql_exception,
lo_connection type ref to cl_sql_connection,
lo_statement type ref to cl_sql_statement,
lo_result_set type ref to cl_sql_result_set.
clear: os_data, o_error_msg.
get reference of l_mandt into l_mandt_ref.
get reference of os_data into l_result_ref.
l_mandt = '222'. "i.e. select from client 222
l_tabname = i_tabname.
try.
lo_connection = cl_sql_connection=>get_connection( ).
lo_statement = lo_connection->create_statement( ).
* Set criteria for select:
lo_statement->set_param( l_mandt_ref ).
concatenate
'select * from' l_tabname
'where mandt = ?'
into l_sql_statement separated by space.
* Execute
call method lo_statement->execute_query
exporting
statement = l_sql_statement
hold_cursor = space
receiving
result_set = lo_result_set.
* Get the data from the resultset.
lo_result_set->set_param_struct( l_result_ref ).
while lo_result_set->next( ) > 0.
write: / os_data.
endwhile.
* Tidy up:
lo_result_set->close( ).
lo_connection->close( ).
catch cx_sql_exception into lo_cx_sql.
o_error_msg = lo_cx_sql->get_text( ).
catch cx_root into lo_cx_root.
o_error_msg = lo_cx_root->get_text( ).
endtry.
endform. -
XSU and CURSOR expression in the sql query
Platform: oracle 8.X on ibm aix and java client code from
windows NT.
JDBC DRIVER: JDBC Oracle thin driver version 1.2.
when i execute a Sql satement with Cursor expression from the
java client code with XSU it returns an XML DOM But if the
CURSOR EXPRESSION IN THE SQL QUERY RETURNS EMPTY ROWS i get
back an error node with "ORA-01001 Invalid Cursor" error
message.i had aslo set the setNullAttributes(true) property
on oraclexmlquery.
Interestingly, if i exceute the same query in the SQL plus
it returns the column names with no rows.
is there any way where i can get xml document with table
structure, when there are no rows instead of ORA error message.Ok.
I assume that you have for one activity several asset PNR and for one asset several activity.
The factPNR is on this way a real bridge table. It's a way to be able to design a many-to-many relationship.
Have a look here for more detail on how to build a many-to-many relationship :
http://gerardnico.com/wiki/dw/data_quality/relationships#many-to-many
Therefore I assume that you want this design :
DimActivity -< FactActivity >- < FactPNR >- DimPNR and you will have :
DimActivity -< FactActivity >- < BridgeTable >- DimPNR How to build your bridge table ?
In the physical layer, :
* create a new table BridgeActivityPNR, open it and select "statement"
* enter your sql statement
SELECT DISTINCT A.ROW_WID ACTIVIDAD_WID, B.ROW_WID ASSET_WID
FROM W_ACTIVITY_F A,
W_ASSET_D B,
W_SRVREQ_D C,
X_S_CMPT_MTRC_F D,
X_S_ASSET_FEA_D E
WHERE A.X_SRA_SR_ID=C.INTEGRATION_ID AND
C.X_VLG_FLIGHT_ID=D.X_ROW_ID AND
D.X_ROW_ID=E.X_CM_ID AND
E.X_ASSET_ID=B.X_ROW_ID* add two columns in the column tab : ACTIVIDAD_WID and ASSET_WID
* create the physical join with the table FactActivity and DimPNR
* drag and drop in the business model your table BridgeActivityPNR
* in the BMM, create the complex join like this :
DimActivity -< FactActivity >- < BridgeTable >- DimPNR * open your logical bridge table and check the bridge table option.
And you are done if I didn't forget anything.
A complete example here :
http://gerardnico.com/wiki/dat/obiee/obiee_bridge_table -
Dynamic XML TAGS in PL/SQL
Hi I wish to have dynamic xml tags in pl/sql e.g. say i have a table xml_table with xml_tag and tag_value as two columns. Let us say it has a rows
XML_TAG = timezone
TAG_VALUE = UK
I want the output in the following format
<timezone>UK</timezone>.
Any ideas how to achieve it using ORACLE functions and not concatenate <> to the columns? Help would be much appreciated.This is a forum discussing questions related to Oracle Portal. I'd recommend you to take a look at XDB and XSQL, on Oracle's Web site at http://otn.oracle.com.
Hope it helps,
Peter -
Create a cursor from a PL/SQL variable or an external file
Dear friends,
is there a way for me to make Oracle Forms read a cursor from a PL/SQL variable, or an external file? Let's suppose we have the code below:
DECLARE
cursor c_values is select * from my_table;
r_values c_values%ROWTYPE;
BEGIN
for r_values in c_values loop
do_something;
end loop;
END;
In the situation described above, could I create "select * from my_table" from a PL/SQL variable (it could be something like p_cursor = 'select * from my_table'), or an external file - for example, make my form read the contents of c:\my_select.sql , where we see the "select * from my table" text?
My question comes because I need to export data from select instructions that were dinamically created inside the form - that is, via PL/SQL -, and I don't want to rewrite it, but I'll have to do it if I have no choice. Your help will be greatly appreciated.
Best regards,
Franklin
Edited by: franklinbrasil on 12/03/2009 11:33
Edited by: franklinbrasil on 12/03/2009 11:35Dear friends,
I am using DBMS_SQL package, which solved my problem. Please let me explain it better, if it's not clear.
I have some PL/SQL blocks inside my form, which creates SQL queries dinamically, and a dinamically created SQL is stored into a VARCHAR2 variable. These SQL queries are exported for use in Oracle Graphics, but since OG is not being developed by Oracle anymore then I am trying to find a substitute for it.
So I thought about creating an option for the final user: he/she can choose exporting data into Microsoft Excel, and user does what he/she wants, creating a customized graphic. Exporting into Excel works finely, with no problems at all - I could find a routine by searching on the web.
My goal was to use the same queries created above to export data dinamically to Microsoft Excel, and I absolutely don't want to rewrite all these dinamically created queries - one which works dinamically, other with no flexibility inside my form. Worse than it, I have many other dinamically created queries, and I obviously don't want to rewrite them all - any maintenance in this form would be terrible, with each SQL instruction written twice.
Since all dinamically created SQL instructions are stored inside a VARCHAR2 variable, I thought about reusing the same SQL, as explained above - and here we have your suggestions about using a ref cursor, execute immediate, and so on. And (answering Andreas) query structure is always based on the same table, but its structure changes a lot, depending on what the final user chooses in a drop-down list (it's a list of graphics options, where final user chooses one option, and form must mount SQL dinamically, based on user's choice).
By using your explanations, I could find DBMS_SQL solution here: http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96590/adg09dyn.htm#26799
. Please notice that I had to change DBMS_SQL.native into 1 for it to work in my form. I'll mark all your answers as helpful because I can use them both for database and form purposes.
If my message was not clear enough, please tell me and I'll try to make it more clear.
Best regards,
Franklin -
Dynamic Date dimensions in MS Sql Server 2005
Environment : BO 4 SP3
Database : MS Sql 2005
Trying to create dynamic date universe with MS Sql as back end.
But when I try creating current year month dated class, it returns error :
Parse failed: Exception : DBD, [Microsoft SQL Server Native Client 10.0] : Incorrect syntax near 'From'.State:42000
I tested the universe connection which is working fine as evident from below screenshot :
BusinessObjects Configuration
Version 3.2.1.80
Build 14.1.1.1036
Network Layer OLE DB
DBMS Engine MS SQL Server 2008
Language en
Charset CP1252
Library D:\Programs\BusinessObjects4\SAP BusinessObjects Enterprise XI 4.0\dataAccess\connectionServer\drivers\lib32\dbd_wsqloledb.dll
SBO D:\Programs\BusinessObjects4\SAP BusinessObjects Enterprise XI 4.0\dataAccess\connectionServer\oledb\sqlsrv.sbo
RSS D:\Programs\BusinessObjects4\SAP BusinessObjects Enterprise XI 4.0\dataAccess\connectionServer\oledb\sqlsrv.rss
PRM D:\Programs\BusinessObjects4\SAP BusinessObjects Enterprise XI 4.0\dataAccess\connectionServer\oledb\sqlsrv.prm
Strategies Not Defined
Middleware and DBMS Configuration
Driver architecture 32
Charset UCS2
Driver name Microsoft SQL Server Native Client 10.0
Driver version 10.50.1600.1
Provider file name sqlncli10.dll
OLE DB Version 02.80
DBMS name Microsoft SQL Server
DBMS version 09.00.5069Per SAP Note 1241422 - Database fragmentation and reindexing improves performance
Summary
Symptom
During the lifetime of a database (any db not only SAP Business One) and due to insert\update\delete of data, the information in indexes is fragmented. Fragmentation exists when indexes have pages in which the logical ordering, based on the key value, does not match the physical ordering inside the data file. Heavily fragmented indexes can cause slow performance.
Other terms
Index, performance, re-index, reindex, slow, poor, DB
Reason and Prerequisites
FAQ
Solution
It is recommended to run a rebuild the following procedure once\twice a month: -
Hi,
I'm trying to work on dynamic cursors.
When I try to execute the below code, I'm getting the following error.
BEGIN
DYNAMIC_CURSOR.OPENCURSOR();
END;
exception raised ORA-00932: inconsistent datatypes: expected - got -
Below is my code:
CREATE OR REPLACE
PACKAGE BODY dynamic_cursor AS
PROCEDURE dyn_sel (
tab_name IN VARCHAR2,
field_name IN VARCHAR2,
val IN VARCHAR2,
crs IN OUT t_crs)
IS
stmt VARCHAR2(200);
BEGIN
stmt := 'select * from '|| tab_name || ' where '|| field_name || ' = :1';
OPEN crs FOR stmt USING val;
END dyn_sel;
PROCEDURE openCursor IS
tc t_crs;
f1 VARCHAR2(50);
f2 VARCHAR2(50);
BEGIN
dyn_sel ('EMP','JOB','MANAGER', tc);
LOOP
FETCH tc INTO f1, f2;
EXIT WHEN tc%notfound;
dbms_output.put_line (f2);
END LOOP;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line ('exception raised '||SQLERRM);
END openCursor;
END dynamic_cursor; -ThanksThe selected columns must match the INTO clause, so you need to exactly fetch two columns as e.g. in
stmt := 'select ename, job from ' || tab_name || ' where ' || field_name || ' = :1';
....
Maybe you are looking for
-
I have an iMac running OS 10.4.11. How can I check to see if I have the Flashback Trojan (and remove it, if I have it)? IMy Safari is also crashing frequently. Any suggestions?
-
Regarding digital signature in adobe
hai everybody, I am using a signature field in the pdf form in webdynpro. When user enters the signature how can i get that digital signature in webdynpro application .In which format it will be returned . Can u please suggest any
-
Home button is sticky...
Recently it started sticking, it feels like something is under the top portion of the small round button. So essentially I have to press it really hard multiple times to get it to function which is just out right annoying. I don't see how anything, e
-
Mac Bound to Active Directory won't let users download
Good Morning, We have a handful of Macs running in a Windows 2008 server environment bound to AD. When our users log in they cannot download any type of file. This is an issue as most of our users are students trying to download their school work f
-
ANN: JFreeChart 0.9.6
A new version of JFreeChart, a popular free chart library for Java, has been posted at: http://www.object-refinery.com/jfreechart/index.html This release fixes bugs from the recent 0.9.5 release. JFreeChart is free software under the terms of the GNU