I create one PL/SQL procedure i want simple show two messages? - plsql

The PL/SQL procedure below:
'DECLARE
V_EMPNO NUMBER(10):=&EMPNO;
V_EMPNO2 NUMBER(10):= 0;
CURSOR C1 IS SELECT EMPNO FROM EMP;
BEGIN
FOR I IN C1 LOOP
FETCH C1 INTO V_EMPNO2;
EXIT WHEN C1%FOUND;
END LOOP;
IF (LENGTH(V_EMPNO)) > 4 THEN
DBMS_OUTPUT.PUT_LINE ('LENGTH OF EMPNO GREATER THAN 4 NUMBER');
ELSIF (V_EMPNO = V_EMPNO2) THEN
DBMS_OUTPUT.PUT_LINE ('THIS EMPLOYEE NUMBER ALREADY EXIST');
END IF;
END;
/'
In this procedure I want show two messages
one is if lenght greater than number 4 than show message
and second is if v_empno = v_empno2 then show second message
empno = v_empno then show message:
DBMS_OUTPUT.PUT_LINE ('THIS EMPLOYEE NUMBER ALREADY EXIST')
this is error
Enter value for empno: 4444
DECLARE
*
ERROR at line 1:
ORA-01001: invalid cursor
ORA-06512: at line 7

FOR I IN C1 LOOP
already implicitly opens c1 and handles the fetching, so your explicit fetch after it is invalid.
btw i is normally used for numeric indexes rather than records.
Also your caps lock was on when you wrote that code ;)

I think there are a couple of problems with your code.
C1 does not restrict on employee number (meaning the loop will
return a single, largely random row from table emp
You are mixing FOR LOOP and FETCH syntax
Variable v_empno is a NUMBER and you need to be careful when checking the length - you need to explicitly TO_CHAR and control the format - often TO_CHAR will end up including space characters (an alternative would be to check the value of a number is < 10000)
I've not tested this code but this might be closer to what you're after :
DECLARE
l_empno NUMBER := &empno ;
CURSOR C_get_emp
IS
SELECT e.empno
FROM emp e
WHERE e.empno = l_empno
;
R_emp C_get_emp%ROWTYPE ;
BEGIN
IF LENGTH(TRIM(TO_CHAR(l_empno))) > 4 THEN
DBMS_OUTPUT.put_line('Length of empno > 4') ;
ELSE
OPEN C_get_emp ;
FETCH C_get_emp INTO R_emp ;
IF C_get_emp%FOUND THEN
DBMS_OUTPUT.put_line('Employee number already exists') ;
END IF ;
CLOSE C_get_emp ;
END IF ;
END ;

Related

How to use the for loop in fetching Id's from a rows in a table to be used by a procedure in PLSQL?

This is my code below I get this error(Error at line 24/8: ORA-06550: line 20, column 12:PLS-00201: identifier 'A.ID' must be declared) as shown in the image below when I try running the code. Please how can I write the plsql code properly(using for loop) to fetch each row ID and pass them to the procedure?
BEGIN
DECLARE
p_id number(30);
p_status varchar(20);
BEGIN
for c in (
SELECT
a.ID,
a.STATUS
INTO
p_id,
p_status
from USER_COMMISSIONS a,
order_line b where a.order_line_id=b.id and a.status= 'unconfirmed'
)
LOOP
begin
p_id := a.ID;
p_status := a.STATUS;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
end;
-- update pstk_payload set status = 'done' where id = pyld_id;
dbms_output.put_line(p_id);
-- PSTK_PAYMENT_PACKAGE.add_payment(p_amt, p_user_id, p_reference, p_name, p_narration, p_payment_date, p_net_amt, p_payment_type_id, p_transaction_type_id, p_payment_id, p_status);
END LOOP;
end;
END;
There's nothing to declare, actually - everything you need (at least, in code you posted and that's not commented) is contained in cursor itself.
As William commented, you need to reference columns with the cursor name (not tables that are their source).
Also, no need for any exception handler; cursor certainly won't return no_data_found; if its select doesn't return anything the only "consequence" will be that none of commands within the loop will be executed.
If you're joining tables, then use JOIN; leave where clause for conditions (if any).
Therefore:
begin
for c in (select a.id,
a.status
from user_commissions a join order_line b on a.order_line_id = b.id
where a.status= 'unconfirmed'
)
loop
dbms_output.put_line(c.id ||', '|| c.status);
end loop;
end;

Can anyone help whey my execption section is not working,

My whole intention to catch exception,WRONG parameter is NOT CATCHING exception.
Here is the code:
CREATE OR REPLACE PROCEDURE list_emp (p_emp_id IN employees.employee_id%TYPE,
p_dept_id IN employees.department_id%TYPE)
IS
CURSOR c1 IS
SELECT *
FROM EMPLOYEES
WHERE EMPLOYEE_ID=p_emp_id
AND DEPARTMENT_ID=p_dept_id;
emp_rec c1%ROWTYPE;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO emp_rec;
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(emp_rec.employee_id||' '||emp_rec.first_name||' '||emp_rec.last_name);
END LOOP;
CLOSE c1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No Record Found ');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('No Record Found ');
END;
When the cursor is opened and fetched with the wrong parameter that does not match any row from the corresponding table, the following line
EXIT WHEN c1%NOTFOUND;
cause the plsql procedure to terminate (because there were no rows found). Hence no exception is raised.
If you do want to display some sort of output you can do the following instead
IF c1%FOUND THEN
dbms_output.put_line('Record Found');
ELSE
dbms_output.put_line('Finished/Done');
EXIT;
END IF;
If you want to raise an error after looping through a cursor that returns no rows, then you're going to have to use a counter to work out how many rows have been processed, and then you can do something if no rows have been processed.
Something like:
create or replace procedure list_emp (p_emp_id in employees.employee_id%type,
p_dept_id in employees.department_id%type)
is
cursor c1 is
select employee_id,
first_name,
last_name
from employees
where employee_id = p_emp_id
and department_id = p_dept_id;
v_count number := 0;
begin
for emp_rec in c1
loop
v_count := v_count + 1;
dbms_output.put_line(emp_rec.employee_id||' '||emp_rec.first_name||' '||emp_rec.last_name);
end loop;
if v_count = 0 then
raise no_data_found;
end if;
exception
when no_data_found then
dbms_output.put_line('No Record Found.');
raise;
when others then
dbms_output.put_line('An error occurred: '||sqlerrm);
raise;
end;
/
A few notes:
I converted your cursor loop into a cursor-for-loop; you don't need to worry about declaring the record type and also Oracle handles the opening and closing of the cursor for you.
I added raise; to each of your exception handlers - in general, having when others then null (which is effectively what your original code was doing - no errors are raised to the calling code) is a bad idea. I added the raise to the no_data_found condition as that wasn't doing anything either; typically, if you have an exception condition, you want it to do something to let the calling code know there was a problem (not always, of course; sometimes you don't want the processing to stop if a particular error condition is met).
Your cursor was selecting all columns, but in your procedure, you were only using three of them. I've therefore amended the cursor so that it only pulls back those three columns.
Don't rely on dbms_output in your production code. Code that calls this procedure won't see anything populated in dbms_output, unless it explicitly looks for it - and that's not something I've ever seen in any production code, outside of Database tools (eg. SQL*Plus, Toad, etc). I've left this in your procedure as I've a feeling this is a learning exercise for you, but please don't think that this is in any way acceptable in production code.
You're passing p_emp_id in as a parameter - typically, that's the primary key of the employees table. If that's the case, then there's no need for the cursor for loop at all - you could do it by using select ... into ... instead, like so:
.
create or replace procedure list_emp (p_emp_id in employees.employee_id%type,
p_dept_id in employees.department_id%type)
is
v_emp_id employees.employee_id%type;
v_first_name employees.first_name%type;
v_last_name employees.last_name%type;
begin
select employee_id,
first_name,
last_name
into v_emp_id,
v_first_name,
v_last_name
from employees
where employee_id = p_emp_id
and department_id = p_dept_id;
dbms_output.put_line(emp_rec.employee_id||' '||emp_rec.first_name||' '||emp_rec.last_name);
exception
when no_data_found then
dbms_output.put_line('No Record Found.');
raise;
when others then
dbms_output.put_line('An error occurred: '||sqlerrm);
raise;
end;
/
Alternatively, just pass back a ref cursor:
create or replace procedure list_emp (p_emp_id in employees.employee_id%type,
p_dept_id in employees.department_id%type,
p_ref_cur out sys_refcursor)
is
begin
open p_ref_cur for select employee_id,
first_name,
last_name
from employees
where employee_id = p_emp_id
and department_id = p_dept_id;
-- No need for an exception handler here since you're not storing the error details anyway.
-- By not having an error handler, any error will automatically be raised up to the calling code
-- and it will have the correct error stack trace info (e.g. the line number the error occurred,
-- rather than the line the error was reraised from
end;
/
And to run the ref cursor in SQL*Plus (or as a script in Toad/SQL Developer/etc), you do the following:
-- create a variable outside of PL/SQL to hold the ref cursor pointer (this is a SQL*Plus command):
variable rc refcursor;
-- populate our ref cursor variable with the pointer. Note how we pass it in as a bind variable
begin
list_emp(p_emp_id => 1234,
p_dept_id => 10,
p_ref_cur => :rc);
end;
/
-- finally, print the contents of the ref cursor.
print rc;

PL/SQL Cursor just check if value is greater than a value

I want
to make a procedure check if exist empno from table employees
with emno greater than 100. If exist at least one, i want
to exit from the loop.
How can I modify the following code ?
Is it problem I don;t use %NOTFOUND , %ROWCOUNT ?
CREATE OR REPLACE procedure check_value
IS
cursor c1 is
select *
from employess;
c1_values c1%ROWTYPE;
BEGIN
open c1;
fetch c1 into c1_values;
loop
if c1_values.EMPNO > 100 then
DBMS_OUTPUT.put_line ('Found row with empno > 100');
end if;
end loop;
close c1;
END;
If you just need to check if you have a record which has empno over 100 you can use EXISTS statement e.g.
DECLARE
CURSOR c1 IS
SELECT
CASE
WHEN EXISTS (
SELECT
1
FROM
employees
WHERE
empno > 100
) THEN 1
ELSE 0
END AS empno_exists
FROM
dual;
ln_empno_exists PLS_INTEGER;
BEGIN
OPEN c1;
FETCH c1 INTO ln_empno_exists;
CLOSE c1;
DBMS_OUTPUT.PUT_LINE('Empno over 100 exists: '||CASE WHEN ln_empno_exists = 1 THEN 'TRUE' ELSE 'FALSE' END);
END;
/
EDIT: If you want to fetch the rows with some conditions, you simply need to adjust your WHERE clause in your SELECT statement. Here you have an example with some ways to iterate through the records fetched:
DECLARE
CURSOR c1 IS
SELECT
emp.*
FROM
employees emp
WHERE
empno > 100
;
lr_c1_rec c1%ROWTYPE;
BEGIN
-- Using FOR loop
DBMS_OUTPUT.PUT_LINE('START: Printing employees records where empno > 100');
FOR rec IN c1
LOOP
DBMS_OUTPUT.PUT_LINE('empno = '||rec.empno);
END LOOP;
DBMS_OUTPUT.PUT_LINE('END: Printing employees records where empno > 100');
-- Using a LOOP with EXIT clause
DBMS_OUTPUT.PUT_LINE('START: Printing employees records where empno > 100');
OPEN c1;
LOOP
FETCH c1 INTO lr_c1_rec;
-- exit the loop when your cursor doesn't have any more records to be returned
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('empno = '||lr_c1_rec.empno);
END LOOP;
DBMS_OUTPUT.PUT_LINE('END: Printing employees records where empno > 100');
-- Using WHILE loop
DBMS_OUTPUT.PUT_LINE('START: Printing employees records where empno > 100');
OPEN c1;
FETCH c1 INTO lr_c1_rec;
-- As long as cursor returns any values, iterate through the records returned
WHILE c1%FOUND
LOOP
DBMS_OUTPUT.PUT_LINE('empno = '||lr_c1_rec.empno);
END LOOP;
DBMS_OUTPUT.PUT_LINE('END: Printing employees records where empno > 100');
END;
/
Just add an EXIT statement after you've found your value:
CREATE OR REPLACE procedure check_value IS
cursor c1 is
select *
from employess;
c1_values c1%ROWTYPE;
BEGIN
open c1;
loop
fetch c1 into c1_values;
IF c1%NOTFOUND THEN EXIT;
if c1_values.EMPNO > 100 then
DBMS_OUTPUT.put_line ('Found row with empno > 100');
EXIT;
end if;
end loop;
-- The EXIT statement will drop you out of the loop and leave you here
close c1;
END;
Note that I moved the fetch inside the loop and added a %NOTFOUND check. Without the %NOTFOUND the code would never know the cursor was out of data and would probably go into an infinite loop.
Why to define cursor and then open and fetch when it can be done by just
SQL But if it is required so then use FOR loop and EXIT condition
as mentioned
below. Hope it helps
CREATE OR REPLACE PROCEDURE check_value
IS
BEGIN
FOR I IN
(SELECT * FROM employess
)
LOOP
IF I.EMPNO > 5 THEN
DBMS_OUTPUT.put_line ('Found row with empno > 100');
EXIT;
END IF;
END LOOP;
END;

Can I pass an explicit cursor to a function/procedure for use in FOR loop?

I have a procedure that performs some calculations on all records returned by a cursor. It looks a bit like this:
PROCEDURE do_calc(id table.id_column%TYPE)
IS
CURSOR c IS
SELECT col1, col2, col3
FROM table
WHERE ...;
BEGIN
FOR r IN c LOOP
-- do some complicated calculations using r.col1, r.col2, r.col3 etc.
END LOOP;
END;
Now I have the case where I need to perform the exact same calculation on a different set of records that come from a different table. However, these have the same "shape" as in the above in example.
Is it possible to write a procedure that looks like this:
PROCEDURE do_calc2(c some_cursor_type)
IS
BEGIN
FOR r IN c LOOP
-- do the calc, knowing we have r.col1, r.col2, r.col3, etc.
END LOOP;
END;
I know about SYS_REFCURSOR, but I was wondering if it was possible to use the much more convenient FOR ... LOOP syntax and implicit record type.
Create a package.
Declare your cursor as package variable.
Use %rowtype to set function parameter type.
create or replace package test is
cursor c is select 1 as one, 2 as two from dual;
procedure test1;
function test2(test_record c%ROWTYPE) return number;
end test;
create or replace package body test is
procedure test1 is
begin
for r in c loop
dbms_output.put_line(test2(r));
end loop;
end;
function test2(test_record c%ROWTYPE) return number is
l_summ number;
begin
l_summ := test_record.one + test_record.two;
return l_summ;
end;
end test;
I had a similar problem, where I had two cursors that needed to be processed the same way, so this is how I figured it out.
DECLARE
--Define our own rowType
TYPE employeeRowType IS RECORD (
f_name VARCHAR2(30),
l_name VARCHAR2(30));
--Define our ref cursor type
--If we didn't need our own rowType, we could have this: RETURN employees%ROWTYPE
TYPE empcurtyp IS REF CURSOR RETURN employeeRowType;
--Processes the cursors
PROCEDURE process_emp_cv (emp_cv IN empcurtyp) IS
person employeeRowType;
BEGIN
LOOP
FETCH emp_cv INTO person;
EXIT WHEN emp_cv%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Name = ' || person.f_name ||
' ' || person.l_name);
END LOOP;
END;
--Defines the cursors
PROCEDURE mainProcedure IS
emp empcurtyp;
BEGIN
OPEN emp FOR SELECT first_name, last_name FROM employees WHERE salary > 50000;
process_emp_cv(emp);
CLOSE emp;
OPEN emp FOR SELECT first_name, last_name FROM kuren WHERE first_name LIKE 'J%';
process_emp_cv(emp);
CLOSE emp;
END;
BEGIN
mainProcedure;
END;
/
You can also use this if you want to bulk collect your cursors. You just need to change your helper procedure process_emp_cv; the rest can stay the same.
Using BULK COLLECT
--Processes the cursors
PROCEDURE process_emp_cv (emp_cv IN empcurtyp) IS
TYPE t_employeeRowTable IS TABLE OF employeeRowType;
employeeTable t_employeeRowTable;
BEGIN
LOOP
FETCH emp_cv BULK COLLECT INTO employeeTable LIMIT 50;
FOR indx IN 1 .. employeeTable.Count
LOOP
DBMS_OUTPUT.PUT_LINE('Name = ' || employeeTable(indx).f_name ||
' ' || employeeTable(indx).l_name);
END LOOP;
EXIT WHEN emp_cv%NOTFOUND;
END LOOP;
END;
Try this one, Usong ref cursor.
declare
type c is ref cursor;
c2 c;
type rec is record(
id number,
name varchar(20)
);
r rec;
procedure p1(c1 in out c,r1 in out rec)is begin
loop
fetch c1 into r1;
exit when c1%notfound;
dbms_output.put_line(r1.id || ' ' ||r1.name);
end loop;
end;
begin
open c2 for select id, name from student;
p1(c2,r);
end;
Yes you can use Cursor explicitly into procedure and function,for that cursor need to declare into package as variable

plsql cursor iterating problem

i use oracle demo schema scott to do some plsql test ( the data in that schema are never changed ). i wrote the following program to get the employee number of each department. the problem is, there is just 4 departments but my program output 5 row. i can't find out the reason, anyone can help? great thanks.
declare
cursor employees(department_id number) is
select count(*) howmany
from scott.emp
where deptno=department_id;
employees_per_dept employees%rowtype;
cursor departments is
select *
from scott.dept;
a_department departments%rowtype;
begin
dbms_output.put_line('-----------------------------------');
open departments;
loop
exit when departments%notfound;
fetch departments into a_department;
open employees(a_department.deptno);
fetch employees into employees_per_dept;
dbms_output.put_line(employees_per_dept.howmany);
close employees;
end loop;
close departments;
dbms_output.put_line('-----------------------------------');
end;
If you output the deptno in the dbms_output you'll see the reason.
You need to switch these two lines:
fetch departments into a_department;
exit when departments%notfound;
%NOTFOUND is meaningless before the initial FETCH; your code was counting the emps in the last dept twice.
declare
cursor cl(ccode varchar2) is
Select * from employees where department_id=ccode;
z cl%rowtype;
cnt number:=0;
begin
Open cl('90');
fetch cl into Z;
while (cl%found) loop
dbms_output.put_line ( 'nsme is ' || z.last_name);
fetch cl into Z;
cnt := cnt +1;
end loop;
dbms_output.put_line (cnt);
close cl;
end;

Resources