PROCEDURE getEmployeeDetails(EmpID IN NUMBER,
EmpSalary OUT NUMBER) Is
BEGIN
SELECT Salary
into EmpSalary
FROM Employee_accounts_master
WHERE Emp_ID = EmpID
AND SALARY = 'B';
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line(-20001);
When the above query fetches no rows, This procedure throws an NO_DATA_FOUND Exception. Instead of throwing this exception, I need to do some other update/insert process. How to achieve this.
Testing for the existence of records is one instance where explicit cursors can be useful.
PROCEDURE getEmployeeDetails(EmpID IN NUMBER,
EmpSalary OUT NUMBER)
IS
cursor c_emp (p_EmpID NUMBER) is
SELECT Salary
FROM Employee_accounts_master
WHERE Emp_ID = p_EmpID
AND SALARY = 'B';
r_Emp c_emp%rowtype;
BEGIN
open c_emp(EmpID);
fetch c_emp into r_emp;
if c_emp%NOTFOUND then
insert into employee (emp_id) values (EmpID);
end if;
close c_emp;
END;
Alternatively you can use a MERGE statement, but just coding a WHEN NOT MATCHED THEN INSERT branch. Find out more.
Just do it in exception section, check the below:
Begin
BEGIN
SELECT Salary
into EmpSalary
FROM Employee_accounts_master
WHERE Emp_ID = EmpID
AND SALARY = 'B';
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- use the label
goto myinsert;
end;
-- here is your line 67 code starts
<<myinsert>>
-- your insert statement, for eg.
insert into emp (empno) values (1);
end;
Related
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;
I need to create a trigger that when the last employee of the dept is deleted from emp table, the dept is deleted from the dept table.
emp(empno, ename, deptno)
dept(deptno, dname)
First, I created a procedure that deletes the dept from dept table given a deptno.
CREATE OR REPLACE PROCEDURE del_dept
(v_dno in number)
is
begin
delete from DEPT where deptno = v_dno;
end;
Then I created a trigger that deletes the dept when the last emp in that dept is deleted. I tried to test the trigger by deleting one of the three emps in deptno10, but I got error mesg from command that trigger is invalid and failed re-validation.
create or replace trigger del_dept
after delete on EMP
for each row
DECLARE
emp_count Number;
g_dno Number;
begin
SELECT COUNT(:old.ename) INTO emp_count FROM emp group by deptno;
FOR i IN 1.. emp_count LOOP
IF i = emp_count THEN
del_dept(g_dno);
end if;
END LOOP;
End;
Error trigger is invalid and failed re-validation specifies that yor trigger was created with compilation error hence you were not able to test it. This is not a good idea to write a trigger in your case. I can see few issues in you code. So lets first resolve these issues.
When you write the code below, your trigger would be compiled and would be a valid one. So you will not get the error trigger is invalid and failed re-validation
CREATE OR REPLACE TRIGGER del_dept
AFTER DELETE
ON EMP
FOR EACH ROW
DECLARE
EMP_CNT NUMBER;
BEGIN
SELECT COUNT (1)
INTO emp_cnt
FROM emp
WHERE deptno = :old.deptno;
IF emp_cnt = 0
THEN
---del_dept is your procedure to delete records from dept table
del_dept (:old.deptno);
END IF;
END;
But when you would try to execute it you will further get the error:
ORA-04091: table EMP is mutating, trigger/function may not see it
ORA-06512: at "DEL_DEPT", line 4 ORA-04088: error during execution of
trigger 'DEL_DEPT'
The reason for getting this error is you are trying to select from the table from which you are deleting records and thats not allowed in oracle.
The best way for your case is to write a procedure which would delete the records once the last employee data is deleted from your dept table . See below:
CREATE OR REPLACE PROCEDURE del_dept (dept_no NUMBER)
IS
EMP_CNT NUMBER;
BEGIN
SELECT COUNT (1)
INTO emp_cnt
FROM emp
WHERE deptno = dept_no;
IF emp_cnt = 0
THEN
del_dept (dept_no);
END IF;
END;
I want to update all the tables having ABC column.Need to skip the tables which doesn't have data.I am having problem in checking the count of the table in a cursor loop.
PLSQL code
create or replace procedure testp is
CURSOR c_testp
IS
SELECT table_name,
column_name
FROM all_tab_columns
WHERE column_name IN('ABC')
ORDER BY table_name;
c int;
BEGIN
FOR table_rec IN c_testp
LOOP
BEGIN
SELECT COUNT(*)
INTO c
FROM table_rec.table_name;
IF(c>0) THEN
query := 'update '||table_rec.table_name||' set '||table_rec.column_name ||'= xyz';
EXECUTE IMMEDIATE query;
COMMIT;
END IF;
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('data not found');
WHEN OTHERS THEN
dbms_output.put_line('others');
END;
END LOOP;
END;
In your code, use this:
EXECUTE IMMEDIATE 'SELECT count(*) FROM ' || table_rec.table_name INTO c;
instead of this:
SELECT COUNT(*)
INTO c
FROM table_rec.table_name;
However, as mentioned in comments - there is actually no need to perform that condition check, as no update will be performed when table is empty.
I have a table that includes customer ID and order ID and some other data.
I want to create a procedure that takes customer ID as input and look inside the table.
if that customer exists then print the order details for that customer and
if customer does not exist then raise an exception "Customer not found."
I have this code, but it's not working properly, or maybe I have the wrong approach to this question.
CREATE OR REPLACE PROCEDURE order_details(customer NUMBER)
IS
CURSOR order_cursor IS
SELECT ORDER_ID, ORDER_DATE, TOTAL, CUSTOMER_ID
FROM PRODUCT_ORDER
WHERE CUSTOMER_ID = customer ;
order_row order_cursor%ROWTYPE ;
customer_error EXCEPTION ;
BEGIN
FOR order_row IN order_cursor
LOOP
IF order_cursor%FOUND THEN
dbms_output.put_line ('order id = ' || order_row.ORDER_ID) ;
ELSE
RAISE customer_error ;
END IF;
END LOOP;
EXCEPTION
WHEN customer_error THEN
dbms_output.put_line ('no customer' ) ;
END;
So if I run the procedure with this line
BEGIN
order_details(103);
END;
I get two results because order exists for this customer.
and if I run the procedure with this line
BEGIN
order_details(101);
END;
I don't get anything (not even the error ) because there is no order for that customer.
Table Data
You must use an "Explicit Cursor" instead of "Cursor FOR LOOP". Because the latter just enter the code between LOOP and END LOOP when the query returns more than one record.
CREATE OR REPLACE PROCEDURE order_details(customer NUMBER)
IS
CURSOR order_cursor IS
SELECT ORDER_ID, ORDER_DATE, TOTAL, CUSTOMER_ID
FROM PRODUCT_ORDER
WHERE CUSTOMER_ID = customer ;
order_row order_cursor%ROWTYPE ;
customer_error EXCEPTION ;
BEGIN
OPEN order_cursor;
LOOP
FETCH order_cursor INTO order_row;
EXIT WHEN order_cursor%NOTFOUND;
dbms_output.put_line ('order id = ' || order_row.ORDER_ID);
END LOOP;
IF order_cursor%rowcount = 0 THEN
RAISE customer_error;
END IF;
CLOSE order_cursor;
EXCEPTION
WHEN customer_error THEN
dbms_output.put_line ('no customer' ) ;
END;
Regards
My trigger wants to check if a 'new' manager supervises no more than 5 employees.
Manager supervising only 5 people are in BLOCKED_MANAGER table(ssn,numberofemployees).
Finally, every update is recorded in SUPERLOG table(date,user,old_manager,new_manager).
I get no compiling error about the trigger, but when I update a superssn I get this error:
SQL> update employee set superssn='666666607' where ssn='111111100';
update employee set superssn='666666607' where ssn='111111100'
*
ERROR at line 1:
ORA-04091: Table FRANK.EMPLOYEE is mutating, the trigger/function
can't read it
ORA-06512: a "FRANK.TLOG", line 20
ORA-04088: error during execution of trigger 'FRANK.TLOG'
How can I solve this trigger? Thank you
create or replace trigger tlog
before update of superssn on employee
for each row
declare
t1 exception;
n number:=0;
cont number:=0;
empl varchar2(16);
cursor cur is (select ssn from blocked_manager where ssn is not null);
begin
open cur;
loop
fetch cur into empl;
exit when cur%notfound;
if(:new.superssn = empl) then
n:=1;
end if;
end loop;
close cur;
if n=1 then
raise t1;
end if;
select count(*) into cont from employee group by superssn having superssn=:new.superssn;
if(cont=4) then
insert into blocked_manager values(:new.superssn,5);
end if;
insert into superlog values(sysdate,user,:old.superssn, :new.superssn );
exception
when t1 then
raise_application_error(-20003,'Manager '||:new.superssn||' has already 5 employees');
end;
Probably the quickest way around this is to use a carefully constructed statement trigger instead of a row trigger. Row triggers have the phrase FOR EACH ROW in them, are invoked for each row which is modified (based on the BEFORE/AFTER INSERT, BEFORE/AFTER UPDATE, and BEFORE/AFTER DELETE constraints on the trigger), can see the appropriate :NEW and :OLD values, and are subject to the "can't look at the table on which the trigger is defined" rule. Statement triggers are invoked at the appropriate time for each statement which is executed, can't see row values, but aren't subject to the limits on looking at the particular table on which they're defined. So for the portions of your logic which don't need to work with :NEW or :OLD values a trigger such as this might prove useful:
CREATE OR REPLACE TRIGGER EMPLOYEE_S_BU
BEFORE UPDATE ON EMPLOYEE
-- Note: no BEFORE EACH ROW phrase, so this is a statement trigger
BEGIN
-- The following FOR loop should insert rows into BLOCKED_MANAGER for all
-- supervisors which have four or more employees under them and who are not
-- already in BLOCKED_MANAGER.
FOR aRow IN (SELECT e.SUPERSSN, COUNT(e.SUPERSSN) AS EMP_COUNT
FROM EMPLOYEE e
LEFT OUTER JOIN BLOCKED_MANAGER b
ON b.SSN = e.SUPERSSN
WHERE b.SSN IS NULL
GROUP BY e.SUPERSSN
HAVING COUNT(e.SUPERSSN) >= 4)
LOOP
INSERT INTO BLOCKED_MANAGER
(SSN, EMPLOYEE_COUNT)
VALUES
(aRow.SUPERSSN, aRow.EMP_COUNT);
END LOOP;
-- Remove rows from BLOCKED_MANAGER for managers who supervise fewer
-- than four employees.
FOR aRow IN (SELECT e.SUPERSSN, COUNT(e.SUPERSSN) AS EMP_COUNT
FROM EMPLOYEE e
INNER JOIN BLOCKED_MANAGER b
ON b.SSN = e.SUPERSSN
GROUP BY e.SUPERSSN
HAVING COUNT(e.SUPERSSN) <= 3)
LOOP
DELETE FROM BLOCKED_MANAGER
WHERE SSN = aRow.SUPERSSN;
END LOOP;
-- Finally, if any supervisor has five or more employees under them,
-- raise an exception. Note that we go directly to EMPLOYEE to determine
-- the number of employees supervised.
FOR aRow IN (SELECT SUPERSSN, COUNT(*) AS EMP_COUNT
FROM EMPLOYEE
GROUP BY SUPERSSN
HAVING COUNT(*) >= 5)
LOOP
-- If we get here we've found a supervisor with 5 (or more) employees.
-- Raise an exception
RAISE_APPLICATION_ERROR(-20000, 'Found supervisor ' || aRow.SUPERSSN ||
' supervising ' || aRow.EMP_COUNT ||
' employees');
END LOOP;
END EMPLOYEE_S_BU;
Note that if you get rid of the BLOCKED_MANAGER table (which this trigger still maintains, although I don't know if it's truly necessary) the logic gets cut down considerably.
You'll still need a row trigger to handle the logging, but as that's just a matter of cutting down your existing trigger I'll leave that to you. :-)
Share and enjoy.
As you have discovered, you cannot select from the same table that a row-level trigger is defined against; it causes a table mutating exception.
In order to properly create this validation using a trigger a procedure should be created to obtain user-specified locks so the validation can be correctly serialized in a multi-user environment.
PROCEDURE request_lock
(p_lockname IN VARCHAR2
,p_lockmode IN INTEGER DEFAULT dbms_lock.x_mode
,p_timeout IN INTEGER DEFAULT 60
,p_release_on_commit IN BOOLEAN DEFAULT TRUE
,p_expiration_secs IN INTEGER DEFAULT 600)
IS
-- dbms_lock.allocate_unique issues implicit commit, so place in its own
-- transaction so it does not affect the caller
PRAGMA AUTONOMOUS_TRANSACTION;
l_lockhandle VARCHAR2(128);
l_return NUMBER;
BEGIN
dbms_lock.allocate_unique
(lockname => p_lockname
,lockhandle => p_lockhandle
,expiration_secs => p_expiration_secs);
l_return := dbms_lock.request
(lockhandle => l_lockhandle
,lockmode => p_lockmode
,timeout => p_timeout
,release_on_commit => p_release_on_commit);
IF (l_return not in (0,4)) THEN
raise_application_error(-20001, 'dbms_lock.request Return Value ' || l_return);
END IF;
-- Must COMMIT an autonomous transaction
COMMIT;
END request_lock;
This procedure can then be used in a compound trigger (assuming at least Oracle 11, this will need to be split into individual triggers in earlier versions)
CREATE OR REPLACE TRIGGER too_many_employees
FOR INSERT OR UPDATE ON employee
COMPOUND TRIGGER
-- Table to hold identifiers of inserted/updated employee supervisors
g_superssns sys.odcivarchar2list;
BEFORE STATEMENT
IS
BEGIN
-- Reset the internal employee supervisor table
g_superssns := sys.odcivarchar2list();
END BEFORE STATEMENT;
AFTER EACH ROW
IS
BEGIN
-- Store the inserted/updated supervisors of employees
IF ( ( INSERTING
AND :new.superssn IS NOT NULL)
OR ( UPDATING
AND ( :new.superssn <> :old.superssn
OR :new.superssn IS NOT NULL AND :old.superssn IS NULL) ) )
THEN
g_superssns.EXTEND;
g_superssns(g_superssns.LAST) := :new.superssn;
END IF;
END AFTER EACH ROW;
AFTER STATEMENT
IS
CURSOR csr_supervisors
IS
SELECT DISTINCT
sup.column_value superssn
FROM TABLE(g_superssns) sup
ORDER BY sup.column_value;
CURSOR csr_constraint_violations
(p_superssn employee.superssn%TYPE)
IS
SELECT count(*) employees
FROM employees
WHERE pch.superssn = p_superssn
HAVING count(*) > 5;
r_constraint_violation csr_constraint_violations%ROWTYPE;
BEGIN
-- Check if for any inserted/updated employee there exists more than
-- 5 employees for the same supervisor. Serialise the constraint for each
-- superssn so concurrent transactions do not affect each other
FOR r_supervisor IN csr_supervisors LOOP
request_lock('TOO_MANY_EMPLOYEES_' || r_supervisor.superssn);
OPEN csr_constraint_violations(r_supervisor.superssn);
FETCH csr_constraint_violations INTO r_constraint_violation;
IF csr_constraint_violations%FOUND THEN
CLOSE csr_constraint_violations;
raise_application_error(-20001, 'Supervisor ' || r_supervisor.superssn || ' now has ' || r_constraint_violation.employees || ' employees');
ELSE
CLOSE csr_constraint_violations;
END IF;
END LOOP;
END AFTER STATEMENT;
END;
You do not need the blocked_manager table to manage this constraint. This information can be derived from the employee table.
Or in versions earlier than Oracle 11i:
CREATE OR REPLACE PACKAGE employees_trg
AS
-- Table to hold identifiers of inserted/updated employee supervisors
g_superssns sys.odcivarchar2list;
END employees_trg;
CREATE OR REPLACE TRIGGER employee_biu
BEFORE INSERT OR UPDATE ON employee
IS
BEGIN
-- Reset the internal employee supervisor table
employees_trg.g_superssns := sys.odcivarchar2list();
END;
CREATE OR REPLACE TRIGGER employee_aiur
AFTER INSERT OR UPDATE ON employee
FOR EACH ROW
IS
BEGIN
-- Store the inserted/updated supervisors of employees
IF ( ( INSERTING
AND :new.superssn IS NOT NULL)
OR ( UPDATING
AND ( :new.superssn <> :old.superssn
OR :new.superssn IS NOT NULL AND :old.superssn IS NULL) ) )
THEN
employees_trg.g_superssns.EXTEND;
employees_trg.g_superssns(employees_trg.g_superssns.LAST) := :new.superssn;
END IF;
END;
CREATE OR REPLACE TRIGGER employee_aiu
AFTER INSERT OR UPDATE ON employee
IS
DECLARE
CURSOR csr_supervisors
IS
SELECT DISTINCT
sup.column_value superssn
FROM TABLE(employees_trg.g_superssns) sup
ORDER BY sup.column_value;
CURSOR csr_constraint_violations
(p_superssn employee.superssn%TYPE)
IS
SELECT count(*) employees
FROM employees
WHERE pch.superssn = p_superssn
HAVING count(*) > 5;
r_constraint_violation csr_constraint_violations%ROWTYPE;
BEGIN
-- Check if for any inserted/updated employee there exists more than
-- 5 employees for the same supervisor. Serialise the constraint for each
-- superssn so concurrent transactions do not affect each other
FOR r_supervisor IN csr_supervisors LOOP
request_lock('TOO_MANY_EMPLOYEES_' || r_supervisor.superssn);
OPEN csr_constraint_violations(r_supervisor.superssn);
FETCH csr_constraint_violations INTO r_constraint_violation;
IF csr_constraint_violations%FOUND THEN
CLOSE csr_constraint_violations;
raise_application_error(-20001, 'Supervisor ' || r_supervisor.superssn || ' now has ' || r_constraint_violation.employees || ' employees');
ELSE
CLOSE csr_constraint_violations;
END IF;
END LOOP;
END;