"Bulk Collect Into" and "Execute Immediate" in Oracle - oracle

is it possible to execute the "bulk Collect into" with the "execute immediate" commands in oracle? All of that would be part of a function that returns a pipe lined table as a result.

Yes, technically you can:
1 SQL> declare
2 type x is table of t.id%type index by pls_integer;
3 xx x;
4 begin
5 execute immediate
6 'select id from t' bulk collect into xx;
7 dbms_output.put_line(xx.count);
8 end;
9 /
426
And Oracle clearly states this in the documentation:
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/executeimmediate_statement.htm
But you can use more useful way event if you really NEED to execute Dynamic SQL - weak ref cursors. You will have the access to such powerful option as LIMIT and will be able to use collections of records.
SQL> declare
2 type x is table of t%rowtype index by pls_integer;
3 xx x;
4 c sys_refcursor;
5 begin
6 open c for 'select * from t';
7 loop
8 fetch c bulk collect into xx limit 100;
9 dbms_output.put_line(xx.count);
10 exit when c%notfound;
11 end loop;
12 close c;
13 end;
14 /
100
100
100
100
26

Following the idea proposed by Dmitry Nikiforov I solved the problem using cursors and here is the solution ;)
FUNCTION myFunction ( parameter_p IN VARCHAR2) RETURN myTableType PIPELINED
IS
c sys_refcursor;
stmt varchar2(4000);
out_rec mYrowType;
rec mYrowType;
BEGIN
stmt:='Select * from ''' || parameter_p || '''';
open c for stmt;
LOOP
fetch c into rec;
EXIT WHEN c%NOTFOUND;
out_rec.field1 := rec.field1;
out_rec.field2 := rec.field2;
out_rec.field3 := rec.field3;
PIPE Row(out_rec);
END LOOP;
Close c;
Return;
END myFunction;

Related

Oracle Dynamically call cursor

I've two cursors both have almost similar code just a little difference in the group by condition, I want if the id is 1 or 2 e.t.c then it should open cur1 else cur2, basically one cursor at a time. Is there any possibility of achieving this?
if id in (1,2,3,4) then
cursor_value:= 'cur1';
else
cursor_value := 'cur2';
end if;
for i in cursor_value loop
end loop;
You can use an OPEN-FOR statement. Example:
DECLARE
TYPE EmpCurTyp IS REF CURSOR;
v_emp_cursor EmpCurTyp;
emp_record employees%ROWTYPE;
v_stmt_str VARCHAR2(200);
v_e_job employees.job%TYPE;
BEGIN
-- Dynamic SQL statement with placeholder:
v_stmt_str := 'SELECT * FROM employees WHERE job_id = :j';
-- Open cursor & specify bind argument in USING clause:
OPEN v_emp_cursor FOR v_stmt_str USING 'MANAGER';
-- Fetch rows from result set one at a time:
LOOP
FETCH v_emp_cursor INTO emp_record;
EXIT WHEN v_emp_cursor%NOTFOUND;
END LOOP;
-- Close cursor:
CLOSE v_emp_cursor;
END;
/
One option would be to include both cursor's SELECT statements into cursor FOR loop, along with a condition that chooses which one of them will be used. For example:
SQL> declare
2 id number := &par_id;
3 begin
4 for cur_r in (select * from emp
5 where deptno = 10
6 and id in (1,2,3,4)
7 union all
8 select * from emp
9 where deptno = 20
10 and id not in (1,2,3,4)
11 )
12 loop
13 dbms_output.put_Line(cur_r.deptno ||' '||cur_r.ename);
14 end loop;
15 end;
16 /
Enter value for par_id: 1 --> ID = 1, so use SELECT for DEPTNO = 10
old 2: id number := &par_id;
new 2: id number := 1;
10 CLARK
10 KING
10 MILLER
PL/SQL procedure successfully completed.
SQL> /
Enter value for par_id: 823 --> ID <> 1, so use SELECT for DEPTNO = 20
old 2: id number := &par_id;
new 2: id number := 823;
20 SMITH
20 JONES
20 SCOTT
20 ADAMS
20 FORD
PL/SQL procedure successfully completed.
SQL>
The simple way could be to use if else condition.
DECLARE
type cur REF CURSOR;
c cur;
BEGIN
IF id in (1,2,3,4) THEN
OPEN c FOR 'cursor query 1';
ELSE
OPEN c FOR 'cursor query 2';
END IF ;
END;
Cheers!!

select with variable parameter in the procedure

I am trying to write a procedure with the following functionality. Namely, is looking for records from the tables in the schema. In particular, it is a typepkstring column in these tables. At the same time, I have the composedtypes table on the same schema, which has the column pk. The pk column contains all number identifiers from the aforementioned typepkstring column. And now the problem is that in typepkstring we have additionally keys that are not in the column pk in tabel composedtypes. And I have to search the schema and write it out together with the name of the table in which they are located.
at this point, my procedure looks as follows:
create or replace PROCEDURE SIEROT
(i_table_name VARCHAR2)
is
CURSOR c is
SELECT DISTINCT i_table_name.TYPEPKSTRING
FROM i_table_name
LEFT OUTER JOIN COMPOSEDTYPES
ON i_table_name.TYPEPKSTRING=COMPOSEDTYPES.PK
WHERE COMPOSEDTYPES.PK IS NULL;
TYPE c_list IS TABLE of PRODUCTS.TYPEPKSTRING%type INDEX BY binary_integer;
TYPEPK_list c_list;
counter integer :=0;
BEGIN
FOR n IN c LOOP
counter := counter +1;
TYPEPK_list(counter) := n.TYPEPKSTRING;
dbms_output.put_line('TABLE: '||i_table_name||'('||counter||'):'||TYPEPK_list(counter));
END LOOP;
END;
and calling:
set serveroutput on
DECLARE
ind integer := 0;
BEGIN
FOR ind IN (select table_name from all_tab_columns where column_name='TYPEPKSTRING' AND table_name!='COMPOSEDTYPES')
LOOP
BEGIN
SIEROT(ind.table_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
null;
END;
END LOOP;
END;
this is the second approach to the problem I used, it seemed easier to me. The second one, also not functional, was based on cursors using the array type.
My problem is:
calling certainly works fine, but when I compile the same procedure I get the following error:
Procedure SIEROT compiled
LINE/COL ERROR
--------- -------------------------------------------------------------
5/7 PL/SQL: SQL Statement ignored
6/31 PL/SQL: ORA-00942: table or view does not exist
17/7 PL/SQL: Statement ignored
17/31 PLS-00364: loop index variable 'N' use is invalid
Errors: check compiler log
Same select for permanently entered table names, where I have put 2 records that meet the conditions of the task myself, works correctly:
SELECT DISTINCT TESTOWY.TYPEPKSTRING
FROM TESTOWY
LEFT OUTER JOIN COMPOSEDTYPES
ON TESTOWY.TYPEPKSTRING=COMPOSEDTYPES.PK
WHERE COMPOSEDTYPES.PK IS NULL;
and for select so typed in the procedure, it gets the intended effect but, I need to parameterize the name of the source table if it wants to search all of the whole schema, not just on specific one. Only one of the abovementioned selects would be sufficient for one particular:
TABLE: TESTOWY(1):8790000000098
TABLE: TESTOWY(2):8790000000124
PL/SQL procedure successfully completed.
I really do not have the strength for this procedure. Write me how to improve it to work but also fulfill your opinion. Thanks for any hints or corrections;)
You can't use the value of a parameter as a table name in a query directly - you'll need to build your SELECT statement dynamically and then use a loop to fetch the data:
CREATE OR REPLACE PROCEDURE SIEROT(i_table_name VARCHAR2) IS
strSelect VARCHAR2(32767);
c SYS_REFCURSOR;
vTYPEPKSTRING PRODUCTS.TYPEPKSTRING%TYPE;
TYPE c_list IS TABLE of PRODUCTS.TYPEPKSTRING%type INDEX BY binary_integer;
TYPEPK_list c_list;
counter integer := 0;
BEGIN
strSelect := 'SELECT DISTINCT i.TYPEPKSTRING ' ||
' FROM ' || i_table_name || ' i ' ||
' LEFT OUTER JOIN COMPOSEDTYPES c ' ||
' ON i.TYPEPKSTRING = c.PK ' ||
' WHERE c.PK IS NULL';
OPEN c FOR strSelect;
FETCH c INTO vTYPEPKSTRING;
WHILE c%FOUND LOOP
counter := counter + 1;
TYPEPK_list(counter) := vTYPEPKSTRING;
dbms_output.put_line('TABLE: '||i_table_name||'('||counter||'):'||TYPEPK_list(counter));
FETCH c INTO vTYPEPKSTRING;
END LOOP;
CLOSE c;
EXCEPTION
WHEN OTHERS THEN
IF c%ISOPEN THEN
CLOSE c;
END IF;
END SIEROT;
Best of luck.
You'll have to use dynamic SQL (i.e. execute immediate) here, as table name (passed as a parameter) can't be used in a query. The way you put it, it seems that the whole code in SIEROT procedure should be dynamic.
Here's an example based on Scott's schema (as I don't have your tables):
SQL> set serveroutput on
SQL> create or replace procedure sierot(i_table_name in varchar2)
2 is
3
4 l_str varchar2(2000);
5 l_str_2 varchar2(2000);
6 counter integer := 0;
7 begin
8 l_str := 'select distinct i.empno typepkstring from ' || i_table_name || ' i join dept d on d.deptno = i.deptno
9 where d.deptno = 10';
10
11 l_str_2 := 'declare
12 counter integer := 0;
13 type c_list is table of emp.empno%type index by binary_integer;
14 typepk_list c_list;
15 begin
16 for n in (' || l_str ||') loop
17 counter := counter + 1;
18 typepk_list(counter) := n.typepkstring;
19 dbms_output.put_line(TYPEPK_list(counter));
20 end loop;
21 end;';
22
23 execute immediate l_str_2;
24
25 end;
26 /
Procedure created.
SQL> exec sierot('emp');
7782
7839
7934
PL/SQL procedure successfully completed.
SQL>

Error: cursor already open in nested for loops

create or replace PROCEDURE template2(
template_id_in IN RTEMPLATE_CONFIGURE.TEMPLATE_ID%TYPE)
AS
source_table rtemplate_configure.sobject_name%type;
source_column rtemplate_configure.scolumn_name%type;
target_table rtemplate_configure.tobject_name%type;
target_column rtemplate_configure.tcolumn_name%type;
tmp VARCHAR2(2000);
tmp2 VARCHAR2(2000);
CURSOR c_template_configure is
SELECT * FROM rtemplate_configure WHERE template_id = template_id_in order by source_table, target_table;
BEGIN
FOR record_line in c_template_configure LOOP
FOR record_line2 in c_template_configure LOOP
IF record_line.sobject_name = record_line2.sobject_name
and record_line.tobject_name = record_line2.tobject_name
and record_line.tcolumn_name <> record_line2.tcolumn_name
and record_line.scolumn_name <> record_line2.scolumn_name
THEN
tmp2 := 'INSERT INTO '||record_line.tobject_name||'('||record_line.tcolumn_name||','||record_line2.tcolumn_name||')'||'
SELECT '||record_line.scolumn_name||','||record_line.scolumn_name||'
FROM '||record_line.sobject_name||'';
DBMS_OUTPUT.put_line
(tmp2);
END IF;
END LOOP;
END LOOP;
--COMMIT;
END template2;
I am getting error: PL/SQL: cursor already open, and I closed it properly, I guess? I am not sure if I used for loops properly as well, I just need that one cursor to go through the nested loops to check the data as seen in if statement.
You have opened cursor c_template_configure twice. You can't do that, you'll need to create a copy e.g. c_template_configure2.
Here is a very simple example of what you have done:
SQL> declare
2 cursor c is select * from emp;
3 begin
4 for r1 in c loop -- Open cursor c once
5 for r2 in c loop -- Open cursor c again, already open
6 null;
7 end loop;
8 end loop;
9 end;
10 /
declare
*
ERROR at line 1:
ORA-06511: PL/SQL: cursor already open
ORA-06512: at line 2
ORA-06512: at line 5
Now here is the corrected code:
1 declare
2 cursor c1 is select * from emp;
3 cursor c2 is select * from emp;
4 begin
5 for r1 in c1 loop
6 for r2 in c2 loop
7 null;
8 end loop;
9 end loop;
10* end;
SQL> /
Aside: If processing a lot of data, this is a very inefficient approach. Consider joining the data in the query for example:
select e1.empno as empno1, e2.empno as empno2
from emp e1
cross join emp e2
where e1.empno != e2.empno;
Now you only have 1 cursor to open and it returns all the pairs of employees.
declare
cursor c1 is
select *from emp;
r1 c1%rowtype;
begin
open c1;
fetch c1 into r1;
close c1;
null;
commit;
end;

Access cursor by column name dynamically

Can I access a cursor's column dynamically? I mean by name? something like this:
declare
v_cursor := select * from emp;
begin
FOR reg IN v_cursor LOOP
dbms_output.put_line(**reg['column_name_as_string']**);
end loop;
end;
I know the bold part is not PL/SQL, but I'm looking for something like that and can't find it anywhere.
You can use the package DBMS_SQL to create and access cursors with dynamic queries.
However it's not really straightforward to access a column by name because the DBMS_SQL package uses positioning and in a dynamic query we may not know the order of the columns before the execution.
Furthermore, in the context of this question, it appears that we may not know which column we want to display at compile time, we will assume that the column we want to display is given as a parameter.
We can use DBMS_SQL.describe_columns to analyze the columns of a SELECT query after it has been parsed to build a dynamic mapping of the columns. We will assume that all columns can be cast into VARCHAR2 since we want to display them with DBMS_OUTPUT.
Here's an example:
SQL> CREATE OR REPLACE PROCEDURE display_query_column(p_query VARCHAR2,
2 p_column VARCHAR2) IS
3 l_cursor INTEGER;
4 l_dummy NUMBER;
5 l_description_table dbms_sql.desc_tab3;
6 TYPE column_map_type IS TABLE OF NUMBER INDEX BY VARCHAR2(32767);
7 l_mapping_table column_map_type;
8 l_column_value VARCHAR2(4000);
9 BEGIN
10 l_cursor := dbms_sql.open_cursor;
11 dbms_sql.parse(l_cursor, p_query, dbms_sql.native);
12 -- we build the column mapping
13 dbms_sql.describe_columns3(l_cursor, l_dummy, l_description_table);
14 FOR i IN 1 .. l_description_table.count LOOP
15 l_mapping_table(l_description_table(i).col_name) := i;
16 dbms_sql.define_column(l_cursor, i, l_column_value, 4000);
17 END LOOP;
18 -- main execution loop
19 l_dummy := dbms_sql.execute(l_cursor);
20 LOOP
21 EXIT WHEN dbms_sql.fetch_rows(l_cursor) <= 0;
22 dbms_sql.column_value(l_cursor, l_mapping_table(p_column), l_column_value);
23 dbms_output.put_line(l_column_value);
24 END LOOP;
25 dbms_sql.close_cursor(l_cursor);
26 END;
27 /
Procedure created
We can call this procedure with a query known only at run-time:
SQL> set serveroutput on
SQL> exec display_query_column('SELECT * FROM scott.emp WHERE rownum < 5', 'ENAME');
SMITH
ALLEN
WARD
JONES
PL/SQL procedure successfully completed
SQL> exec display_query_column('SELECT * FROM scott.emp WHERE rownum < 5', 'EMPNO');
7369
7499
7521
7566
PL/SQL procedure successfully completed
Use caution with dynamic SQL: it has the same privileges as the user and can therefore execute any DML and DDL statement allowed for this schema.
For instance, the above procedure could be used to create or drop a table:
SQL> exec display_query_column('CREATE TABLE foo(id number)', '');
begin display_query_column('CREATE TABLE foo(id number)', ''); end;
ORA-01003: aucune instruction analysée
ORA-06512: à "SYS.DBMS_SQL", ligne 1998
ORA-06512: à "APPS.DISPLAY_QUERY_COLUMN", ligne 13
ORA-06512: à ligne 1
SQL> desc foo
Name Type Nullable Default Comments
---- ------ -------- ------- --------
ID NUMBER Y
It's probably easiest to make the query dynamic if you can.
DECLARE
v_cursor SYS_REFCURSOR;
dynamic_column_name VARCHAR2(30) := 'DUMMY';
column_value VARCHAR2(32767);
BEGIN
OPEN v_cursor FOR 'SELECT ' || dynamic_column_name || ' FROM dual';
LOOP
FETCH v_cursor INTO column_value;
EXIT WHEN v_cursor%NOTFOUND;
dbms_output.put_line( column_value );
END LOOP;
CLOSE v_cursor;
END;
If you really want to have a hardcoded SELECT * and dynamically select a column from that by name, I think you could do that using DBMS_SQL as Vincent suggests, but it will be somewhat more complex.
You mean something like:
declare
cursor sel_cur is
select * from someTable;
begin
for rec in sel_cur
loop
dbms_output.put_line('col1: ' || rec.col1);
end loop;
end;

PL/SQL Array to CLOB

i m using Oracle 9i.
I m fetching data from a cursor into an array :
FETCH contract_cur
BULK COLLECT INTO l_contract ;
But now i want to "convert" this l_contract into a CLOB variable l_clob
Is there an easy way to do that?
Or otherwise, how do i convertthe rows from a SELECT statement into one single CLOB Variable ?
thanks
EDIT : i forgot to mention its an array of %ROWTYPE, not just one column.
What an ugly thing to do.
Is it all character data, or do you have numeric and/or date/time values in there too ? If so what format do you want to use for those datatypes when you convert them to strings.
You also may need to think about field and record delimiters.
Have you considered XML ?
declare
v_clob clob;
v_xml xmltype;
begin
select xmlagg(XMLELEMENT("test",xmlforest(id,val)))
into v_xml
from test;
select v_xml.getclobval
into v_clob
from dual;
dbms_output.put_line(v_clob);
end;
/
you can loop through your array and build the CLOB as you go:
SQL> DECLARE
2 TYPE tab_vc IS TABLE OF VARCHAR2(4000);
3 l_contract tab_vc;
4 l_clob CLOB;
5 BEGIN
6 dbms_lob.createtemporary (l_clob, TRUE);
7 SELECT to_char(dbms_random.STRING('a', 1000)) BULK COLLECT
8 INTO l_contract
9 FROM dual
10 CONNECT BY LEVEL <= 100;
11 FOR i IN 1..l_contract.count LOOP
12 dbms_lob.writeappend(l_clob,
13 length(l_contract(i)),
14 l_contract(i));
15 END LOOP;
16 -- your code here
17 dbms_lob.freetemporary(l_clob);
18 END;
19 /
PL/SQL procedure successfully completed
If you don't use l_contract for anything else you can build the CLOB directly from the cursor loop without the array step, it will save memory and will probably be faster:
SQL> DECLARE
2 l_clob CLOB;
3 BEGIN
4 dbms_lob.createtemporary (l_clob, TRUE);
5 FOR cc IN ( SELECT to_char(dbms_random.STRING('a', 1000)) txt
6 FROM dual
7 CONNECT BY LEVEL <= 100) LOOP
8 dbms_lob.writeappend(l_clob,
9 length(cc.txt),
10 cc.txt);
11 END LOOP;
12 -- your code here
13 dbms_lob.freetemporary(l_clob);
14 END;
15 /
PL/SQL procedure successfully completed

Resources