I have three PLSQL functions: A, B and C.
The idea is this: C is calling B, B is calling A.
Function A, when it's called by B, returns a numeric value as a status indicator AND a ref cursor with tabular results.
E.g. function_A (A1 in varchar2, A2 out sys_refcursor) return number;
Function B, when it receives the results from A, is expected to reformat the results before passes them on to C, also in a form of a ref cursor.
A is an existing function and it cannot be amended, while B and C will be completely new functions.
The question is, how do I fetch the ref cursor from A? I was able to get the numeric value returned by the function (i.e the status indicator), but I have problem fetching the results of the ref cursor from A.
If I'm calling A from B, can I assume that the ref cursor of A is automatically opened?
What are the logical steps to get the results from A's ref cursor? E.g. can I fetch the results into an object type?
P/S. I have very limited programming experience and am only few months new in PLSQL.
Any hints will be much appreciated.
Since you have not given us the code functions, we will be based on the description of your functions.
According to the description, you have 3 functions:
Function A.
create or replace function A(A1 in varchar2, A2 out sys_refcursor) return number is
begin
open A2 for select 1 from dual;
return 2;
end;
Function B.
create or replace function B(B1 out sys_refcursor) return number is
cur sys_refcursor;
res_A number;
row_ your_table_a%rowtype;
begin
res_A := A('',cur);
loop
fetch cur into row_;
exit when cur%notfound;
--proccess with row A
end loop;
open B1 for select 2 from dual;
return 1;
end;
Function C
create or replace function C() return number is
res_B number;
cur sys_refcursor;
row_ your_table_b%rowtype;
begin
res_B:= B(cur);
loop
fetch cur into row_;
exit when cur%notfound;
--proccess with row B
end loop;
return 2;
end;
Maybe you can try the below snippet. Tried to replicate the scenario you mentioned in the question. Hope this helps.
CREATE OR REPLACE FUNCTION A_TEST(
A1 IN VARCHAR2,
A2 OUT sys_refcursor )
RETURN NUMBER
AS
lv_num PLS_INTEGER;
BEGIN
NULL;
OPEN a2 FOR SELECT LEVEL FROM DUAL CONNECT BY LEVEL < 19;
RETURN 1;
END;
CREATE OR REPLACE FUNCTION B_TEST
RETURN sys_refcursor
AS
lv_cur sys_refcursor;
lv_num PLS_INTEGER;
BEGIN
lv_num:=A_TEST('AV',lv_cur);
RETURN lv_cur;
END;
CREATE OR REPLACE FUNCTION C_TEST
RETURN sys_refcursor
AS
tab PLS_INTEGER;
lv_cur sys_refcursor;
BEGIN
lv_cur:=B_TEST;
LOOP
FETCH lv_cur INTO tab;
EXIT
WHEN lv_cur%NOTFOUND;
dbms_output.put_line(tab);
END LOOP;
END;
Related
My code:
create table info(str varchar2(30));
declare
cursor c(job emp_ast.job_id%type, dep emp_ast.department_id%type) is select employee_id
from emp_ast
where job_id=job and department_id=dep;
type t_job is table of emp_ast.job_id%type;
t t_job:=t_job();
emp emp_ast.employee_id%type;
i number(3);
begin
select job_id
bulk collect into t
from emp_ast;
for i in 10..270 loop
for j in 1..t.count loop
open c(i, t(j));
loop
fetch c into emp;
insert into info
values (i||' '||t(j)||' '||emp);
exit when c%notfound;
end loop;
i:=i+10;
end loop;
end loop;
end;
/
I get "expression 'I' cannot be used as an assignment target", reffering to the line where I increment i by 10. I am trying to save the department_id, employee_id and job_id as a string in a table for each department and each job.
At the point where you get that message, i refers to the loop control variable i defined in the line for i in 10..270 loop, not the int(3) variable defined earlier. In PL/SQL a loop definition defines a variable which is only accessible inside the loop, and which you cannot alter. I suggest you change the name of one or the other to make them unique.
EDIT
PL/SQL doesn't provide a way to step by more than 1 in a computed FOR loop. Instead, you will need to compute the desired department number value within the loop:
DECLARE
CURSOR c(job EMP_AST.JOB_ID%TYPE,
dep EMP_AST.DEPARTMENT_ID%TYPE)
IS SELECT EMPLOYEE_ID
FROM EMP_AST
WHERE JOB_ID = job AND
DEPARTMENT_ID = dep;
TYPE t_job IS TABLE OF EMP_AST.JOB_ID%TYPE;
t t_job := t_job();
emp EMP_AST.EMPLOYEE_ID%TYPE;
nDepartment NUMBER;
BEGIN
SELECT job_id
BULK COLLECT INTO t
FROM EMP_AST;
FOR i IN 1..27 LOOP
nDepartment := i * 10;
FOR j IN 1..t.COUNT LOOP
OPEN c(t(j), nDepartment);
LOOP
FETCH c INTO emp;
INSERT INTO info
VALUES (nDepartment || ' ' || t(j) || ' ' || emp);
EXIT WHEN c%notfound;
END LOOP; -- cursor c
CLOSE c;
END LOOP; -- j
END LOOP; -- i
END;
/
Note that in the code above the nDepartment value is computed within the i loop, which now increments from 1 to 27 instead of going from 10 to 270.
I am passing c1 value as param to the c2,c3 cursor's , so i am getting duplicate values and how to write better than this code using plsql code?
Declare
cursor cur1;
cursor cur2
is
select * from
where param=c1.param;
cursor cur3
is
select * from
where param=c1.param;
Begin
for c1 loop
for c2(c1.param)
dbms_output(deptno||' '||dname);
for c3(c1.param)
dbms_output(deptno||' '||dname);
end loop;
end loop;
end loop;
End;
So , i am getting duplicate values
deptno dname
10 a
20 b
30 c
10 a
20 b
30 c
Expected output as
deptno dname
10 a
20 b
30 c
can you please help me?
Sounds like you may want a UNION:
Declare
cursor cur1;
cursor cur2 is
select * from X
where param=c1.param
union
select * from Y
where param=c1.param;
Begin
for c1 loop
for c2(c1.param)
dbms_output(deptno||' '||dname);
end loop;
end loop;
End;
(I haven't fixed your invalid code above - presumably your real code is correct or it wouldn't have run at all.)
You probably don't need even 2 cursors, you could do something like:
Declare
cursor cur is
select * from X
where param in (select ...)
union
select * from Y
where param in (select ...)
Begin
for c2 in cur loop
dbms_output(deptno||' '||dname);
end loop;
End;
you can use inner join to avoid cursor looping.
use distinct keyword to get distinct value.
user of rownum keword to get only one row.
eliminate duplicate by group by clause.
How to retrieve list of employees for each department from table EMP into a comma-delimited new table
something like:
[column x:ie deptno] [column y:ie ename]
--------------------------
7 Jesus, María, José
5 Staz, Przemek, Tomek
6 John, Jane, Bob
below table is where I want to put my result from Function concatenate_list compilation
CREATE TABLE Z
(
x NUMBER(2) NOT NULL,
y VARCHAR2 (4000) NOT NULL
);
SET SERVEROUTPUT ON
CREATE OR REPLACE FUNCTION concatenate_list (xy_cursor IN SYS_REFCURSOR)
RETURN VARCHAR2
IS
lret VARCHAR2(30000);
ltemp VARCHAR2(30000);
BEGIN
LOOP
FETCH xy_cursor
INTO ltemp;
EXIT WHEN xy_cursor%notfound;
lret := lret || ',' || ltemp;
END LOOP;
RETURN LTRIM(lret, ',');
END;
/
SHOW ERRORS
how to insert the results from "Function concatenate_lit compile" and get a result as mentioned above.
Maybe using something like this:
INSERT INTO Z( x, y) SELECT e1.x,
concatenate_list(CURSOR(SELECT e2.y FROM EMP e2 WHERE e2.x= e1.x));
but how to set it up form inside the PL/SQL block
This may help you.
declare
type cur_name is ref cursor;
emp_name cur_name;
v_ename emp.ename%type;
v_all_ename varchar2(1000);
v_deptno emp.deptno%type;
cursor c is select deptno,cursor(select ename from emp e where e.deptno=f.deptno) from emp f group by deptno;
begin
open c;
loop
fetch c into v_deptno,emp_name;
exit when c%notfound;
loop
fetch emp_name into v_ename;
exit when emp_name%notfound;
v_all_ename:=v_all_ename||v_ename;
v_all_ename:=v_all_ename||',';
end loop;
dbms_output.put_line(v_deptno||' '||v_all_ename);
v_all_ename:='';
end loop;
close c;
end;
My Problem is that I want to execute a dynamic SQL-Query within PL/SQL where I have a List of IDs as my Array Bind.
In the Oracle-Documentation I found some Examples how to join Lists of Numbers to an DML-Statement. (http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_sql.htm#i996963)
Now I am trying to make the same thing for Select-Statements.
I know that I can use Array-Binds for the execute immediate-Statement. But this has the disadvantage that I must know the exact number of Bind-Variables before executing the Statement. That is the reason why I have to use dbms_sql.
The following Example Returns only one Row, but it should return 3 rows. Does anyone know what the Problem with my Example is?
--TestData:
CREATE TABLE PERSON AS
SELECT LEVEL AS ID, 'Person_'||LEVEL AS NAME
FROM DUAL CONNECT BY LEVEL <= 5;
declare
p_ids dbms_sql.number_table;
c number;
dummy NUMBER;
p_name varchar2(100);
begin
p_ids(1) := 2;
p_ids(2) := 3;
p_ids(3) := 4;
--
c := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(c, 'select name from PERSON where id in(:num_array)', DBMS_SQL.NATIVE);
dbms_sql.define_column(c, 1, p_name, 100);
DBMS_SQL.BIND_ARRAY(c, ':num_array', p_ids);
dummy := DBMS_SQL.EXECUTE(c);
--
loop
exit when dbms_sql.fetch_rows(c) <=0;
dbms_sql.column_value(c, 1, p_name);
dbms_output.put_line(p_name);
end loop;
DBMS_SQL.CLOSE_CURSOR(c);
end;
Here is my current solution for binding multiple values to a Select Statement, maybe someone can need it:
--TestData:
CREATE TABLE PERSON AS
SELECT LEVEL AS ID, 'Person_'||LEVEL AS NAME
FROM DUAL CONNECT BY LEVEL <= 5;
declare
c number;
dummy NUMBER;
p_name varchar2(100);
xml$ varchar2(1000);
begin
--Generate a XML-List instead of dbms_sql.number_table:
xml$ := '<ids><id>2</id><id>3</id><id>4</id></ids>';
--
c := dbms_sql.open_cursor;
--Using XML-Functions for extracting the Values from the XML-String
DBMS_SQL.PARSE(c, 'select name
from PERSON
where id in(select extractvalue(value(x), ''id'')
from table(xmlsequence(xmltype(:ids).extract(''ids/*'')))x)'
, DBMS_SQL.NATIVE);
dbms_sql.define_column(c, 1, p_name, 100);
DBMS_SQL.BIND_variable(c, ':ids', xml$);
dummy := DBMS_SQL.EXECUTE(c);
--
loop
exit when dbms_sql.fetch_rows(c) <=0;
dbms_sql.column_value(c, 1, p_name);
dbms_output.put_line(p_name);
end loop;
DBMS_SQL.CLOSE_CURSOR(c);
end;
IN my oracle database i want to create a function or procedure with cursor which will use dynamic table name.here is my code.
CREATE OR REPLACE Function Findposition ( model_in IN varchar2,model_id IN number) RETURN number IS cnumber number;
TYPE c1 IS REF CURSOR;
c2 c1;
BEGIN
open c2 FOR 'SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rownumber FROM '||model_in;
FOR employee_rec in c2
LOOP
IF employee_rec.id=model_id then
cnumber :=employee_rec.rownumber;
end if;
END LOOP;
close c2;
RETURN cnumber;
END;
help me to solve this problem.IN
There is no need to declare a c1 type for a weakly typed ref cursor. You can just use the SYS_REFCURSOR type.
You can't mix implicit and explicit cursor calls like this. If you are going to OPEN a cursor, you have to FETCH from it in a loop and you have to CLOSE it. You can't OPEN and CLOSE it but then fetch from it in an implicit cursor loop.
You'll have to declare a variable (or variables) to fetch the data into. I declared a record type and an instance of that record but you could just as easily declare two local variables and FETCH into those variables.
ROWID is a reserved word so I used ROWPOS instead.
Putting that together, you can write something like
SQL> ed
Wrote file afiedt.buf
1 CREATE OR REPLACE Function Findposition (
2 model_in IN varchar2,
3 model_id IN number)
4 RETURN number
5 IS
6 cnumber number;
7 c2 sys_refcursor;
8 type result_rec is record (
9 id number,
10 rowpos number
11 );
12 l_result_rec result_rec;
13 BEGIN
14 open c2 FOR 'SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rowpos FROM '||model_in;
15 loop
16 fetch c2 into l_result_rec;
17 exit when c2%notfound;
18 IF l_result_rec.id=model_id
19 then
20 cnumber :=l_result_rec.rowpos;
21 end if;
22 END LOOP;
23 close c2;
24 RETURN cnumber;
25* END;
SQL> /
Function created.
I believe this returns the result you expect
SQL> create table foo( id number );
Table created.
SQL> insert into foo
2 select level * 2
3 from dual
4 connect by level <= 10;
10 rows created.
SQL> select findposition( 'FOO', 8 )
2 from dual;
FINDPOSITION('FOO',8)
---------------------
4
Note that from an efficiency standpoint, you'd be much better off writing this as a single SQL statement rather than opening a cursor and fetching every row from the table every time. If you are determined to use a cursor, you'd want to exit the cursor when you've found the row you're interested in rather than continuing to fetch every row from the table.
From a code clarity standpoint, many of your variable names and data types seem rather odd. Your parameter names seem poorly chosen-- I would not expect model_in to be the name of the input table, for example. Declaring a cursor named c2 is also problematic since it is very non-descriptive.
You can do this, you don't need loop when you are using dynamic query
CREATE OR REPLACE Function Findposition(model_in IN varchar2,model_id IN number)
RETURN number IS
cnumber number;
TYPE c1 IS REF CURSOR;
c2 c1;
BEGIN
open c2 FOR 'SELECT rownumber
FROM (
SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rownumber
FROM '||model_in || '
) WHERE id = ' || model_id;
FETCH c2 INTO cnumber;
close c2;
return cnumber;
END;