Need help in the recursive procedure call - oracle

I have a requirement to write a procedure (that calls itself recursively).
The condition is like:
If the CONTACT NUMBER(assuming it as varchar2) STARTS WITH '100-%', then the procedure should print all the CONTACT NUMBERS that starts with 100 for the given group.
If CONTACT NUMBER starts with '50-%' then it should call recursively.
I have tried writing a sample procedure, but unfortunately not getting the result.
CREATE OR REPLACE TYPE type_t AS
TABLE OF VARCHAR2(100);
CREATE OR REPLACE PROCEDURE proc_test (
in_group IN VARCHAR2,
contact_nmbr OUT VARCHAR2
) AS
v_out type_t := type_t ();
BEGIN
SELECT
contact_id
BULK COLLECT INTO
v_out
FROM
my_table
WHERE
group_id = in_group;
FOR i IN 1..v_out.count LOOP
v_out.extend;
IF
v_out(i) LIKE '100-%'
THEN
contact_nmbr := v_out(i);
ELSIF v_out(i) LIKE '50-%' THEN
proc_test(v_out(i),contact_nmbr);
END IF;
END LOOP;
END;
/
I am not getting the output after running this proc.
DECLARE
in_group VARCHAR2(30) := '123ABC';
contact_nmbr VARCHAR2(30);
BEGIN
proc_test(in_group,contact_nmbr);
dbms_output.put_line(contact_nmbr);
END;
/
This is the sample data in table MY_TABLE
Group_Id Contact_Id
---------------------------------------
001 100-001-01
001 70-001-01
001 100-002-01
001 50-001-01
50-001-01 30-001-01
50-001-01 100-100-01
50-001-01 50-100-01
50-100-01 50-200-01

Couple of issues I can see with your script....
1) You are declaring the in_group to = 123ABC there is no data matching in your sample data so it will never return anything...
in_group VARCHAR2(30) := '123ABC';
2) You do not exit the loop when you successfully find a contact number so unless your last record is a match you will get no output;
3) when you increment the v_out collection on each loop this serves no purpose this does not do any harm but is not necassary
v_out.extend;
So remove the extend and add a exit as below....
CREATE OR REPLACE PROCEDURE proc_test (
in_group IN VARCHAR2,
contact_nmbr OUT VARCHAR2
) AS
v_out type_t := type_t ();
BEGIN
SELECT
contact_id
BULK COLLECT INTO
v_out
FROM
my_table
WHERE
group_id = in_group;
FOR i IN 1..v_out.count LOOP
IF
v_out(i) LIKE '100-%'
THEN
contact_nmbr := v_out(i);
exit;
ELSIF v_out(i) LIKE '50-%' THEN
proc_test(v_out(i),contact_nmbr);
END IF;
END LOOP;
END;
and call with a valid id as below and you should be good to go.
DECLARE
in_group VARCHAR2(30) := '001';
contact_nmbr VARCHAR2(30);
BEGIN
proc_test(in_group,contact_nmbr);
dbms_output.put_line(contact_nmbr);
END;

Related

Using count(*) to fetch more than one row in a SQL Procedure

I'm trying to return the number of rows per invoice_id using a function and procedure. Some invoice_id's have more than one row and I'm not sure how to fetch the count when I execute my procedure. As an example invoice_id(7) has just one row, but invoice_id(100) has four rows of information.
Create or replace function return_num_rows_function(invoice_id_text in varchar2)
Return varchar2
Is inv_id varchar2(20);
Begin
Select count(*)invoice_id into inv_id from invoice_line_items where invoice_id=invoice_id_text;
Return inv_id;
End;
Create or replace procedure return_num_rows (invoice_id_text in varchar2)
Is inv_id varchar(20);
line_item_desc invoice_line_items.line_item_description%type;
Begin
inv_id := return_num_rows_function(invoice_id_text);
If inv_id is not null then
Select count(*)invoice_id, line_item_description into inv_id,line_item_desc
From invoice_line_items where invoice_id = inv_id;
dbms_output.put_line('The number of rows returned:'|| inv_id);
dbms_output.put_line('Item description(s):'|| line_item_desc);
End if;
End;
set serveroutput on;
execute return_num_rows(7);
First of all do not use a string type variable for a numeric one
(invoice_id_text).
For your case it's better to use a procedure instead of called
function ( return_num_rows_function ), since you need two out
arguments returned.
A SQL Select statement cannot be used without Group By with aggegated and non-aggregated columns together ( i.e. don't use this one :
Select count(*) invoice_id, line_item_description
into inv_id,line_item_desc
From invoice_line_items
Where invoice_id = inv_id;
)
So, Try to create below procedures :
SQL> CREATE OR REPLACE Procedure
return_num_rows_proc(
i_invoice_id invoice_line_items.invoice_id%type,
inv_id out pls_integer,
line_item_desc out invoice_line_items.line_item_description%type
) Is
Begin
for c in
(
Select line_item_description
into line_item_desc
From invoice_line_items
Where invoice_id = i_invoice_id
)
loop
line_item_desc := line_item_desc||' '||c.line_item_description;
inv_id := nvl(inv_id,0) + 1;
end loop;
End;
/
SQL> CREATE OR REPLACE Procedure
return_num_rows(
i_invoice_id pls_integer
) Is
inv_id pls_integer;
line_item_desc invoice_line_items.line_item_description%type;
Begin
return_num_rows_proc(i_invoice_id,inv_id,line_item_desc);
If inv_id is not null then
dbms_output.put_line('The number of rows returned:' || inv_id);
dbms_output.put_line('Item description(s):' || line_item_desc);
End if;
End;
/
and call as in your case :
SQL> set serveroutput on;
SQL> execute return_num_rows(7);
Replace inv_id varchar2(20) with inv_id number;
and also if you want to get two outputs from procedure better to use refcursor.

How to read multiple values at one time as an input to single variable in PLSQL?

Could you help me to pass the input values (at execution time: i mean to enter multiple values for single variable at once).
Here is my code for which i am giving one input at a time either hard coded input or single input at time.
declare
type TEmpRec is record (
EmployeeID EMPLOYEES.EMPLOYEE_ID%TYPE,
LastName EMPLOYEES.LAST_NAME%TYPE
);
type TEmpList is table of TEmpRec;
vEmpList TEmpList;
---------
function EmpRec(pEmployeeID EMPLOYEES.EMPLOYEE_ID%TYPE,
pLastName EMPLOYEES.LAST_NAME%TYPE default null) return TEmpRec is
-- Effective "Record constructor"
vResult TEmpRec;
begin
vResult.EmployeeID := pEmployeeID;
vResult.LastName := pLastName;
return vResult;
end;
---------
procedure SearchRecs(pEmpList in out nocopy TEmpList) is -- Nocopy is a hint to pass by reference (pointer, so small) rather than value (actual contents, so big)
vIndex PLS_integer;
begin
if pEmpList is not null then
vIndex := pEmpList.First;
while vIndex is not null -- The "while" approach can be used on sparse collections (where items have been deleted)
loop
begin
select LAST_NAME
into pEmpList(vIndex).LastName
from EMPLOYEES
where EMPLOYEE_ID = pEmpList(vIndex).EmployeeID;
exception
when NO_DATA_FOUND then
pEmpList(vIndex).LastName := 'F'||pEmpList(vIndex).EmployeeID;
end;
vIndex := pEmpList.Next(vIndex);
end loop;
end if;
end;
---------
procedure OutputRecs(pEmpList TEmpList) is
vIndex PLS_integer;
begin
if pEmpList is not null then
vIndex := pEmpList.First;
while vIndex is not null
loop
DBMS_OUTPUT.PUT_LINE ( 'pEmpList(' || vIndex ||') = '|| pEmpList(vIndex).EmployeeID||', '|| pEmpList(vIndex).LastName);
vIndex := pEmpList.Next(vIndex);
end loop;
end if;
end;
begin
vEmpList := TEmpList(EmpRec(100),
EmpRec( 34),
EmpRec(104),
EmpRec(110));
SearchRecs(vEmpList);
OutputRecs(vEmpList);
end;
/
Above program takes input value one at time.
However, i tried as below but unable to succeed.
i tried to give input from console at once like (100,34,104,100) in place of either hard coding the input (or) giving one input at time.
Snippet in DECLARE section:
declare
type TEmpRec is record (
EmployeeID EMPLOYEES.EMPLOYEE_ID%TYPE,
LastName EMPLOYEES.LAST_NAME%TYPE
);
type TEmpList is table of TEmpRec;
v_input TEmpList := TEmpList(&v_input); -- to read multiple input at once
vEmpList TEmpList;
In the final BEGIN section:
BEGIN
FOR j IN v_input.FIRST .. v_input.LAST LOOP
vEmpList := TEmpList(EmpRec(v_input(j).EmployeeID)); --to assign input values to vEmptList
SearchRecs(vEmpList);
OutputRecs(vEmpList);
end loop;
end;
/
Error in DECLARE section:
PLS-00306: wrong number or types of arguments in call to 'TEMPLIST'
Error in LAST BEGIN section:
PLS-00320: the declaration of the type of this expression is incomplete or malformed
As an example: at time, i am able to read multiple input values for same variable but i am unable to pass this as an input but unable to figure out how can make this as an input my main program.
DECLARE
TYPE t IS TABLE OF VARCHAR2(100);
ORDERS t := t(&ORDERS);
BEGIN
FOR j IN ORDERS.FIRST .. ORDERS.LAST LOOP
dbms_output.put_line(ORDERS(j));
END LOOP;
END;
/
Output:
PL/SQL procedure successfully completed.
Enter value for orders: 321,153,678
321
153
678
Thank You.
Since You have a collection of record variable, you need to pass employee_ids and employee last_names separately. How are you planning to pass them in a single shot?.
Here is a sample script which accomplishes something you want with 2 inputs for 3 collection elements.
First, create a collection TYPE and a PIPELINED function to convert comma separated values into Collections - f_convert2.
CREATE TYPE test_type AS TABLE OF VARCHAR2(100);
CREATE OR REPLACE FUNCTION f_convert2(p_list IN VARCHAR2)
RETURN test_type
PIPELINED
AS
l_string LONG := p_list || ',';
l_comma_index PLS_INTEGER;
l_index PLS_INTEGER := 1;
BEGIN
LOOP
l_comma_index := INSTR(l_string, ',', l_index);
EXIT WHEN l_comma_index = 0;
PIPE ROW ( SUBSTR(l_string, l_index, l_comma_index - l_index) );
l_index := l_comma_index + 1;
END LOOP;
RETURN;
END f_convert2;
/
Then in your anonymous blocks pass values for employee_ids and last_name separately.
SET SERVEROUTPUT ON
DECLARE
TYPE temprec IS RECORD ( employeeid employees.employee_id%TYPE,
lastname employees.last_name%TYPE );
TYPE templist IS
TABLE OF temprec;
vemplist templist;
v_no_of_rec NUMBER := 10;
v_empl_ids VARCHAR2(100) := '&empl_ids';
v_empl_lnames VARCHAR2(100) := '&empl_lnames';
BEGIN
SELECT employee_id,last_name
BULK COLLECT
INTO
vemplist
FROM
(
SELECT
ROWNUM rn,
column_value employee_id
FROM
TABLE ( f_convert2(v_empl_ids) )
) a
JOIN (
SELECT
ROWNUM rn,
column_value last_name
FROM
TABLE ( f_convert2(v_empl_lnames) )
) b ON a.rn = b.rn;
FOR i in 1..vemplist.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(vemplist(i).employeeid || ' ' ||vemplist(i).lastname);
END LOOP;
END;
/
Instead of simple JOIN above if you use OUTER JOIN ( FULL or LEFT ), you can handle missing values without writing logic to check each value.

Oracle Stored Procedure

My question is pretty basic but I am complete newbie to stored procedure and need to get around quickly. Any help will be appreciated,
Below is the current stored procedure we have,
PROCEDURE get_something(
type IN VARCHAR2,
value IN VARCHAR2,
i_type OUT VARCHAR2,
i_id OUT VARCHAR2)
AS
TYPE t_array
IS
TABLE OF VARCHAR2(320);
identifers t_array;
column_name VARCHAR2(32);
info_qry VARCHAR2(500);
top_row_qry VARCHAR2(500);
BEGIN
identifers := t_array('ABC');
column_name := get_column_name(type);
info_qry := 'select INS.i_id, INS.model from table1 INS where INS.'||column_name||'='''||value||''' order by INS.version desc';
top_row_qry := 'select * from ('||info_qry||') where rownum<=1';
EXECUTE immediate top_row_qry INTO i_id, i_type;
EXCEPTION
WHEN OTHERS THEN
i_id := NULL;
i_type := NULL;
END get_something;
Now when I execute this procedure, it gives me one record due to the rownum condition.
My requirement is to remove the rownum from the top_row_qry, so result would be multiple rows.
I want to store each field into some variable out of which I will use one of the variable for some comparison in the procedure itself.
So basically i want to store the results which I can later loop over and compare with a list of values.
Also, I need to define the list of values in this procedure itself.
Something like below:
list_of_vals:= t_array('ABC','XYZ');
Can anyone help me on this.
I guess you need to use cursor as OUT parameter for your procedure and later use it for your requirement.
Also for "I need to define the list of values in this procedure itself."
you can use a collection the way I have used in the procedure code (v_array).
You can then use a loop to traverse through multiple values for the v_array.
CREATE ORE REPLACE PROCEDURE get_something(type IN VARCHAR2,
value IN VARCHAR2,
out_param OUT sys_refcursor)
AS
TYPE t_array IS TABLE OF VARCHAR2(320);
v_array t_array:=t_array();
-- identifers t_array;
column_name VARCHAR2(32);
info_qry VARCHAR2(500);
top_row_qry VARCHAR2(500);
BEGIN
--To define multiple values for a collection e.g. ABC, XYZ
v_array.EXTEND(2) ;
v_array(1):='ABC' ;
v_array(2):='XYZ' ;
--identifers := t_array('ABC') ;
column_name := get_column_name(TYPE) ;
info_qry := 'select INS.i_id, INS.model from table1 INS where INS.'||column_name||'='''||VALUE||''' order by INS.version desc';
top_row_qry := 'select * from ('||info_qry||')' ;
OPEN out_param FOR top_row_qry ;
EXCEPTION
WHEN OTHERS THEN
OPEN out_param FOR 'select null, null from dual' ;
END get_something ;
/
--To execute the procedure
DECLARE
lv_type VARCHAR2(200);
lv_id NUMBER;
lv_cur SYS_REFCURSOR;
BEGIN
get_something('param1','param2',lv_cur);
LOOP
FETCH lv_cur INTO lv_id,lv_type;
EXIT WHEN lv_cur%NOTFOUND;
--Do something.....
END LOOP;
END;

Procedure to input number and output varchar2

I need to write a procedure to input let's say a rep_id and then output the rep_name that corresponds to the rep_id.
After that, I need to use another procedure to call the above procedure.
Here is what I have for the first procedure.
create or replace procedure p_inout
(v_rep_id in number)
As
v_first_name varchar2(20);
v_last_name varchar2(20);
begin
select first_name,last_name into v_first_name, v_last_name
from rep
where rep_id = v_rep_id;
dbms_output.put_line(v_first_name||' '||v_last_name);
end p_inout;
/
Execute p_inout(100);
And here is my procedure to call the above procedure
create or replace procedure p_call
is
v_first_name varchar2(20);
v_last_name varchar2(20);
begin
p_inout(100);
dbms_output.put_line(v_first_name||' '||v_last_name);
end p_call;
/
execute p_call
I was able to get the result but one guy told me that my call procedure should be like this
Create or replace procedure p_call
Is
V_name varchar2(20);
Begin
P_inout(100,v_name); --100 is a rep id
Dbms_output.Put_line(v_name);
End;
/
Execute p_call
Doesn't my procedure to call and his call procedure produce the same result?
CREATE TABLE minions (
rep_id DATE CONSTRAINT minions__rep_id__pk PRIMARY KEY,
rep_name NUMBER CONSTRAINT minions__rep_name__nn NOT NULL
CONSTRAINT minions__rep_name__u UNIQUE
)
/
CREATE OR REPLACE PROCEDURE myCatWasSick (
p_rep_id IN minions.rep_id%TYPE,
p_rep_name OUT minions.rep_name%TYPE
)
IS
BEGIN
SELECT rep_name
INTO p_rep_name
FROM minions
WHERE rep_id = p_rep_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
p_rep_name := NULL;
END myCatWasSick;
/
CREATE OR REPLACE PROCEDURE releaseTheBadgers
IS
the_badger NUMBER(10);
BEGIN
myCatWasSick( SYSDATE + 1, the_badger );
// Do something with the_badger.
END releaseTheBadgers;
/

Cursor will not work in package procedure

I am trying to implement this procedure into a package however the package
will not allow me to use the cursor for some reason. Can anyone help? Thank you.
Also when I try to put the procedure into my package a 'enter bind variable' box appears
minus anywhere to input a bind variable and this error
Not found
The requested URL /apex/wwv_flow.show was not found on this server
My code is
PROCEDURE total_calc(p_order NUMBER)
IS
c_price product.unit_price%type;
c_prod_desc product.product_desc%type;
v_total_cost NUMBER := 0;
v_c1 REFCURSOR;
CURSOR c1 IS
SELECT product_desc, unit_price
FROM product
WHERE product_id IN (SELECT fk2_product_id
FROM order_line
WHERE fk1_order_id = p_order);
BEGIN
OPEN c1;
LOOP
FETCH c1 into c_prod_desc, c_price;
dbms_output.put_line(c_prod_desc || ': ' || c_price);
v_total_cost := v_total_cost + c_price;
EXIT WHEN c1%notfound;
END LOOP;
CLOSE c1;
dbms_output.put_line('Total Cost:' || v_total_cost);
END;
Here is the code for the rest of the package
CREATE OR REPLACE PACKAGE orders_salary_manage AS
FUNCTION tax_func (p_sal IN NUMBER)
RETURN NUMBER;
PROCEDURE reduce_price(p_product_id NUMBER, p_sub_price NUMBER);
PROCEDURE increase_price(p_product_id NUMBER, p_add_price NUMBER);
PROCEDURE remove_order(p_order_id NUMBER);
PROCEDURE add_order(p_order_id NUMBER,
p_order_date VARCHAR2,
p_delivery_date VARCHAR2,
p_customer_id NUMBER,
p_employee_id NUMBER,
p_order_type_id NUMBER);
END orders_salary_manage;
CREATE OR REPLACE PACKAGE BODY orders_salary_manage AS
tot_orders NUMBER;
FUNCTION tax_func (p_sal IN NUMBER)
RETURN NUMBER
IS
tax_rate NUMBER := 0;
v_netsal NUMBER := 0;
v_sal NUMBER;
BEGIN
v_sal := p_sal;
IF v_sal > 70000 THEN
tax_rate := (v_sal * 0.4);
v_netsal := v_sal - tax_rate;
END IF;
IF v_sal < 70000 THEN
tax_rate := (v_sal * 0.2);
v_netsal := v_sal - tax_rate;
END IF;
RETURN v_netsal;
END;
PROCEDURE reduce_price(p_product_id NUMBER, p_sub_price NUMBER)
IS v_price NUMBER;
e_invalid_price EXCEPTION;
BEGIN
SELECT unit_price
INTO v_price
FROM product
WHERE product_id = p_product_id;
v_price := v_price - p_sub_price;
IF v_price < 1 THEN
RAISE e_invalid_price;
ELSE
UPDATE product SET unit_price = v_price WHERE product_id = p_product_id;
END IF;
END;
PROCEDURE increase_price(p_product_id NUMBER, p_add_price NUMBER)
IS v_price NUMBER;
BEGIN
SELECT unit_price
INTO v_price
FROM product
WHERE product_id = p_product_id;
v_price := v_price + p_add_price;
UPDATE product SET unit_price = v_price WHERE product_id = p_product_id;
END;
PROCEDURE remove_order(p_order_id NUMBER)
IS
BEGIN
DELETE FROM placed_order WHERE order_id = p_order_id;
DELETE FROM order_line WHERE fk1_order_id = p_order_id;
END;
PROCEDURE add_order(p_order_id NUMBER,
p_order_date VARCHAR2,
p_delivery_date VARCHAR2,
p_customer_id NUMBER,
p_employee_id NUMBER,
p_order_type_id NUMBER)
IS new_order NUMBER;
BEGIN
INSERT INTO placed_order (order_id, order_date, delivery_date, fk1_customer_id, fk2_employee_id, fk3_order_type_id)
VALUES (p_order_id, p_order_date, p_delivery_date, p_customer_id, p_employee_id, p_order_type_id);
END;
END;
This is really confusing.
First off - dbms_output requires special settings for the environment in order to work. And a call to DBMS_OUTPUT.ENABLE, plus packages do have access to a terminal anyway. Packages do not have your process context, they run in the process context of the db -- which runs without a controlling terminal. If you have to write something use a file -- UTL_FILE package is meant for that.
Next
Since you are basically adding up an order, you need a function to return the value.
A procedure is not going to work. As you coded anyway.
Next
v_C1 is not used and makes no sense for your code. You are not returning a refcursor.
Next
You should consider using a schema for tables with generic table names like that when you decalre a variable.
example:
v_foo schema_owner.table_name.column_name%type;
Consider this:
function total_calc(p_order in NUMBER)
return NUMBER
is
c_price product.unit_price%type;
c_prod_desc product.product_desc%type;
v_total_cost NUMBER := 0;
-- lose this: v_c1 REFCURSOR;
CURSOR c1 IS
SELECT product_desc, unit_price
FROM product
WHERE product_id IN (SELECT fk2_product_id
FROM order_line
WHERE fk1_order_id = p_order);
BEGIN
OPEN c1;
LOOP
FETCH c1 into c_prod_desc, c_price;
-- lose this line: dbms_output.put_line(c_prod_desc || ': ' || c_price);
v_total_cost := v_total_cost + c_price;
EXIT WHEN c1%notfound;
END LOOP;
CLOSE c1;
-- lose this line: dbms_output.put_line('Total Cost:' || v_total_cost);
return v_total_cost;
END;
In order for this to work it has to inside a
CREATE OR REPLACE FUNCTION a statement. Then - Added to the db schema by a user with correct permissions to create it.
After all that, then you can run it. Also, there is more to all this package/function creation stuff like using PRAGMAS if somebody needs to run this from SQLPLUS.

Resources