Sqlplus using stored procedures to update a row - oracle

This is what I have so far. When I enter valid data and run it the table updates correctly. When I run it using author numbers that I know don't exist in the table it still runs, and doesn't output the exception statements. Does anyone know why my exceptions don't seem to be working. Any help would be appreciated thanks!
CREATE OR REPLACE PROCEDURE update_authorname
(selected_author_num IN NUMBER,
new_author_first IN CHAR,
new_author_last IN CHAR) AS
BEGIN
UPDATE author
SET author_first = new_author_first, author_last = new_author_last
WHERE author_num = selected_author_num;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
DBMS_OUTPUT.PUT_LINE('No author with this number exists: ' || selected_author_num);
WHEN ROWTYPE_MISMATCH
THEN
DBMS_OUTPUT.PUT_LINE('Error: There was a row type mismatch when updating');
END;
/
This is what I used to call the procedure:
BEGIN
update_authorname(6,'Emma','White');
END;
/

An update statement doesn't throw an exception when the where clause isn't matched, it just fails silently. Instead, you need to check either:
The row exists before trying to update or
The update changed something.
1. The row exists
CREATE OR REPLACE PROCEDURE update_authorname
(selected_author_num IN NUMBER,
new_author_first IN CHAR,
new_author_last IN CHAR) AS
BEGIN
IF NOT EXISTS (SELECT 1 FROM author WHERE author_num = selected_author_num;
DBMS_OUTPUT.PUT_LINE('No author with this number exists: ' || selected_author_num);
ELSE
UPDATE author
SET author_first = new_author_first, author_last = new_author_last
WHERE author_num = selected_author_num;
EXCEPTION
WHEN ROWTYPE_MISMATCH
THEN
DBMS_OUTPUT.PUT_LINE('Error: There was a row type mismatch when updating');
END;
/
2. The update made changes
CREATE OR REPLACE PROCEDURE update_authorname
(selected_author_num IN NUMBER,
new_author_first IN CHAR,
new_author_last IN CHAR) AS
BEGIN
UPDATE author
SET author_first = new_author_first, author_last = new_author_last
WHERE author_num = selected_author_num;
IF ##ROWCOUNT <= 0
DBMS_OUTPUT.PUT_LINE('No author with this number exists: ' || selected_author_num);
EXCEPTION
WHEN ROWTYPE_MISMATCH
THEN
DBMS_OUTPUT.PUT_LINE('Error: There was a row type mismatch when updating');
END;
/
There are certainly other ways to achieve the same result, but these are the two most common.

Related

Oracle Trigger To Check Values On Insert & Update

I am trying to check a value-gap crossed with each other or not. Let me explain with a quick scenario.
Rec 1 : Company AA : Distance Gap -> 100 - 200
Rec 2 : Company AA : Distance Gap -> 200 - 300 VALID
Rec 3 : Company AA : Distance Gap -> 250 - 450 INVALID
Rec 4 : Company JL : Distance Gap -> 250 - 450 VALID
Rec 3 Invalid because it is between REC 2's distance values.
Rec 4 Valid because company is different
Thus I wrote a trigger to prevent it.
create or replace trigger ab_redemption_billing_mpr
after insert or update on redemption_billing_mpr
for each row
declare
v_is_distance_range_valid boolean;
begin
v_is_distance_range_valid := p_redemption_billing.is_distance_range_valid(:new.id,
:new.redemption_billing_company,
:new.distance_min,
:new.distance_max,
'redemption_billing_mpr');
if not v_is_distance_range_valid then
raise_application_error(-20001, 'This is a custom error');
end if;
end ab_redemption_billing_mpr;
FUNCTION:
function is_distance_range_valid(p_id in number,
p_company in varchar2,
p_distance_min in number,
p_distance_max in number,
p_table_name in varchar2) return boolean is
d_record_number number;
begin
execute immediate 'select count(*) from ' || p_table_name || ' r
where r.redemption_billing_company = :1
and (:2 between r.distance_min and r.distance_max or :3 between r.distance_min and r.distance_max)
and r.id = nvl(:4, id)'
into d_record_number
using p_company, p_distance_min, p_distance_max, p_id;
if (d_record_number > 0) then
return false;
else
return true;
end if;
end;
is_distance_range_valid() works just as I expected. If it returns false, that means range check is not valid and don't insert or update.
When I create a scenario to catch this exception, oracle gives
ORA-04091: table name is mutating, trigger/function may not see it
and it points select count(*) line when I click debug button.
I don't know why I am getting this error. Thanks in advance.
Just check whether the below approach resolves your issue
Create a log table with columns required for finding the is_distance_range_valid validation and In your trigger insert into this log tab.The trigger on main table has to be a before insert or update trigger
Create a trigger on this log table and do the validation in the log table trigger and raise error.The trigger on log table has to be an after insert or update trigger.
Also this will only work if the row is already existing in the main table and it is not part of the current insert or update. If validation of the current insert or update is required then we need to use the :new.column_name to do the validation
Test:-
create table t_trg( n number);
create table t_trg_log( n number);
create or replace trigger trg_t
before insert or update on t_trg
for each row
declare
l_cnt number;
begin
insert into t_trg_log values(:new.n);
end trg_t;
create or replace trigger trg_t_log
after insert or update on t_trg_log
for each row
declare
l_cnt number;
begin
select count(1) into l_cnt from t_trg
where n=:new.n;
if l_cnt > 0 then
raise_application_error(-20001, 'This is a custom error');
end if;
end trg_t_log;
The first time I insert it doesn't throw error
insert into t_trg values(7);
1 row inserted.
The second time I execute, I get the custom error
insert into t_trg values(7);
Error report -
ORA-20001: This is a custom error
ORA-06512: at "TRG_T_LOG", line 7
ORA-04088: error during execution of trigger 'TRG_T_LOG'
ORA-06512: at "TRG_T", line 4
ORA-04088: error during execution of trigger 'TRG_T'
Update:-Using compound trigger the error is thrown in the first time the insert is done since it also takes into account the current row that we are updating or inserting while doing the SELECT
First I want to thanks to psaraj12 for his effort.
I found solution. Oracle forces us to not use select query before each row.
Oracle trigger error ORA-04091
So I wrote this and it works.
create or replace trigger ab_redemption_billing_mpr
for insert or update on redemption_billing_mpr
compound trigger
v_is_distance_range_valid boolean;
id redemption_billing_mpr.id%type;
redemption_billing_company redemption_billing_mpr.redemption_billing_company%type;
distance_min redemption_billing_mpr.distance_min%type;
distance_max redemption_billing_mpr.distance_max%type;
after each row is
begin
id := :new.id;
redemption_billing_company := :new.redemption_billing_company;
distance_min := :new.distance_min;
distance_max := :new.distance_max;
end after each row;
after statement is
begin
v_is_distance_range_valid := p_redemption_billing.is_distance_range_valid(id,
redemption_billing_company,
distance_min,
distance_max,
'redemption_billing_mpr');
if not v_is_distance_range_valid then
raise_application_error(-20001, 'This is a custom error');
end if;
end after statement;
end ab_redemption_billing_mpr;
We must use compound trigger to deal with it.

WHEN-BUTTON-PRESSED trigger raise unhendled exception ORA-01407

I am new in PL SQL and I am trying to resolve problem with copy-past data from .CVS file to database
I create a small application which will take data from .CVS and past it to database.
I create a method, but after I compile it's writtend Successfully compiled
But when I run form I get error
WHEN-BUTTON-PRESSED trigger raise unhendled exception ORA-01407
Does anyone know what this means since I google it and could not find anything ?
I would be very thankfull
declare
import_file text_io.file_type;
import_file_name varchar2(1000);
import_log_file text_io.file_type;
import_log_file_name varchar2(1000);
vec_importovano number;
brojac number;
brojac_redova number;
linebuf varchar2(5000);
p_rbr varchar2(4);
p_polica varchar2(20);
p_banka varchar2 (20);
p_kontakt varchar2(20);
kraj_fajla number;
begin
import_file_name := :Global.Lokacija_prenosa||:import.naziv_fajla||:Global.Ekstenzija_prenosa;
import_file := text_io.fopen(import_file_name,'r');
--p_rbr := 100000;
delete from zivot_trajni_nalog_ponude where banka is not null;
commit;
kraj_fajla := 0;
while kraj_fajla = 0 loop
begin
text_io.get_line(import_file, linebuf);
if brojac_redova>=2 then
if length(linebuf)>100 then
p_rbr:=substr(linebuf, 1, instr(linebuf,';',1,1)-1);
p_polica:=substr(linebuf, instr(linebuf,';',1,1)+1, instr(linebuf,';',1,2) - instr(linebuf,';',1,1)-1);
p_banka:=substr(linebuf, instr(linebuf,';',1,2)+1, instr(linebuf,';',1,3) - instr(linebuf,';',1,2)-1);
p_kontakt:=substr(linebuf, instr(linebuf,';',1,3)+1, instr(linebuf,';',1,4) - instr(linebuf,';',1,3)-1);
select count(*)
into vec_importovano
from ZIVOT_TRAJNI_NALOG_PONUDE
where broj_police=p_polica and p_rbr=redni_broj;
if vec_importovano=0 then
insert into ZIVOT_TRAJNI_NALOG_PONUDE values(p_rbr, p_polica, p_banka, p_kontakt);
commit;
end if;
end if;
end if;
EXCEPTION WHEN NO_DATA_FOUND THEN kraj_fajla := 1;
end;
end loop;
update zivot_trajni_nalog_ponude set redni_broj = p_rbr;
commit;
text_io.fclose(import_file);
message('Zavrseno prepisivanje fajla');
end;
The error you got (ORA-01407) means that you are trying to update a column (which is set to NOT NULL) with a NULL value. That won't work. For example:
SQL> create table test (id number not null);
Table created.
SQL> insert into test (id) values (100);
1 row created.
SQL> update test set id = null;
update test set id = null
*
ERROR at line 1:
ORA-01407: cannot update ("SCOTT"."TEST"."ID") to NULL
SQL>
The only UPDATE in your code is this:
UPDATE zivot_trajni_nalog_ponude SET redni_broj = p_rbr;
Apparently, p_rbr is NULL, redni_broj won't accept it and you got the error.
What to do? Debug your code and see why p_rbr doesn't have a value. A simple "solution" might be
IF p_rbr IS NOT NULL
THEN
UPDATE zivot_trajni_nalog_ponude
SET redni_broj = p_rbr;
END IF;
Also, although not related to your problem: don't COMMIT within a loop.
ORA-01407 occurs as you are trying to update/Insert a column to NULL
when the column does not accept NULL values.
To find all the "not null" columns in table ZIVOT_TRAJNI_NALOG_PONUDE, Please check the DDL of the table.

ORA-01722: invalid number Error - 1

I'm stuck and can't see what the problem is.
I created a procedure with some logic stuff and it compiled successfully, but when I call it in a trigger on my table, it fails with ORA-01722: invalid number.
Any help would be gratefully received.
Here is the procedure:
create or replace Procedure Check_Plants_Fields(
field_id IN number ,
farmer_name IN varchar2,
planting_date IN date DEFAULT sysdate,
planting_amount IN number,
plant_type IN number)
IS
l_plant_type XXLA_PLANTS_TYPE.PLANT_TYPE%type;
l_number_of_months XXLA_PLANTS_SUPPLIERS.NUMBER_MONTHS_TO_CUT%type;
cursor c1 is
SELECT PLANT_TYPE , AMOUNT_
FROM XXLA_PLANTS_TYPE
WHERE PLANT_ID = plant_type;
cursor c2 is
SELECT to_number(MOD(Round(DBMS_RANDOM.Value(1, 8)), 9) + 1)
FROM DUAL;
BEGIN
open c1;
open c2;
fetch c2 into l_number_of_months;
if c1 %notfound then
close c1;
dbms_output.put_line('You dont have this type, please supply it to your store . ' || ' ' || 'thanx.');
end if;
for i in (SELECT PLANT_TYPE , AMOUNT_
FROM XXLA_PLANTS_TYPE
WHERE PLANT_ID = plant_type)
LOOP
if i.AMOUNT_ < 20 then
dbms_output.put_line(i.AMOUNT_ ||' AMOUNT_: '|| i.AMOUNT_);
UPDATE XXLA_PLANTS_SUPPLIERS
SET supplier_id = supplier_id_seq.nextval;
INSERT INTO XXLA_PLANTS_SUPPLIERS
(supplier_id, supplier_name, number_months_to_cut, date_,amount, price_in_KG)
VALUES (supplier_id_seq.nextval, 'Benefits etc',l_number_of_months ,sysdate+1, 80 + i.AMOUNT_,'500$');
end if;
END LOOP i;
commit;
close c2;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered,- '||SQLCODE||' -ERROR- -->'||SQLERRM );
END;
And here is the trigger:
create or replace TRIGGER xxbefor_insert_plants
BEFORE INSERT ON XXLA_PLANT_FIELDS
FOR EACH ROW
BEGIN
Check_Plants_Fields(:NEW.field_id, :NEW.farmer_name, :NEW.planting_date, :NEW.planting_amount, :NEW.plant_type);
END;
Here is the insert that executes the trigger that calls the procedure, but it errors when I run it.
INSERT INTO XXLA_PLANT_FIELDS
(field_id, FARMER_NAME,planting_date,planting_amount,plant_type )
VALUES
(4, 'Test1',sysdate,8,1 (because this parameter it should work its under 20 ));
ORA-01722: invalid number is quite a simple error to understand. It means you are attempting to cast a string to a number datatype but the operation fails because the string contains non-numeric characters.
So what this means is that somewhere in your procedure you have a implicit type conversion. You haven't provided the description of the tables so we can't tell you where the problem happens. You'll have to discover it for yourself.
Two places where it might be:
WHERE PLANT_ID = plant_type if XXLA_PLANTS_TYPE.PLANT_ID is not
numeric
VALUES (... '500$'); if
XXLA_PLANTS_SUPPLIERS.PRICE_IN_KG is not numeric
Incidentally, if you removed that pointless exception handler you would get the default error stack. That would tell you the starting line number of the failing statement, which would really remove a lot of the guesswork from the exercise.

Exception Handling SQL

I created a user defined function that calculates the quantity in stock for a product
CREATE OR REPLACE FUNCTION function_quantityInStock(
oldProductQuantity IN INTEGER,
orderedQuan IN INTEGER)
RETURN INTEGER
IS
v_newQuantity INTEGER;
v_oldQuantity INTEGER;
v_orderedQuan INTEGER;
BEGIN
v_newquantity := oldProductQuantity - orderedQuan;
RETURN v_newquantity;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('Please check your data.');
END function_quantityInstock;
I then create a trigger that updates the table by calling the function
CREATE OR REPLACE TRIGGER TRIGGER_QUANTITY AFTER INSERT ON ordered_product
FOR EACH ROW
DECLARE
v_oldQuantity INTEGER;
BEGIN
SELECT PRODUCT_QUANTITYINSTOCK INTO v_oldQuantity
FROM product
WHERE product_id = :NEW.product_id;
UPDATE PRODUCT
SET product_quantityinstock =
function_quantityINSTOCK(v_oldQuantity, :NEW.ORDERED_PRODUCTQUANTITY)
WHERE product_id = :NEW.product_id;
END;
I want to display a message when the user enters invalid data but my exception block doesnt do that.
I use the following anonyomus block to test the function:
SET SERVEROUTPUT ON;
DECLARE
v_productID ordered_product.product_id%TYPE:= &ProductID;
v_orderID ordered_product.order_id%TYPE:=&OrderID;
v_orderedQuan ordered_product.ordered_productQuantity%TYPE := &OrderedProductQuantity;
v_totalCost ordered_product.ordered_productTotalCost%TYPE := '&TotalCost';
BEGIN
INSERT INTO ordered_product VALUES
(v_orderID, v_productID, v_orderedQuan, v_totalCost);
dbms_output.put_line('A new record has been inserted.');
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line('Invalid data!');
WHEN VALUE_ERROR THEN
dbms_output.put_line('Error! Please check your values.'|| SQLERRM);
END;
You might be missing exec dbms_output.enable(10000) and therefore not be seeing the output.
You should throw the exception using
raise_application_error(-20000, 'Please check your data.');
Also it's bad practice to catch all exceptions using when others and then ignore them.
If I were you, I wouldn't rely on dbms_output.put_line to pass information around. Instead, rely on the standard exception handling, e.g. RAISE or RAISE_APPLICATION_ERROR. Also, given that you're trying to find the new quantity, I'd move the select on the product table into the function, something like:
CREATE OR REPLACE FUNCTION function_quantityinstock(p_product_id IN product.product_product_id p_orderedquan IN INTEGER)
RETURN INTEGER IS
v_newquantity INTEGER;
e_not_enough_stock EXCEPTION;
e_not_enough_stock_num INTEGER := -20001;
e_no_product_exists_num INTEGER := -20002;
PRAGMA EXCEPTION_INIT(e_not_enough_stock, -20001);
BEGIN
SELECT product_quantityinstock - orderedquan
INTO v_newquantity
FROM product
WHERE product_id = :new.product_id;
IF v_newquantity < 0
THEN
RAISE e_not_enough_stock;
END IF;
RETURN v_newquantity;
EXCEPTION
WHEN no_data_found THEN
raise_application_error(-e_no_product_exists_num,
'No product exists for product_id = ' || product_id);
-- no need to check for TOO_MANY_ROWS if product_id is the primary/unique key on the product table.
WHEN e_not_enough_stock THEN
raise_application_error(e_not_enough_stock_num,
'Not enough stock present to fulfil the order for product_id = ' ||
product_id);
WHEN OTHERS THEN
raise_application_error(SQLCODE,
'Unexpected error occurred whilst finding new quantity for product_id = ' ||
product_id || ': ' || SQLERRM);
END function_quantityinstock;
/
You'd need to change the function name though, to reflect the action that it's doing, since it's returning the new quantity in stock...

ORACLE PL/SQL Programming Trigger problems

I'm trying to figure out a simple ORACLE PL/SQL programming problem and I'm having some difficulties with it.
I have to make a trigger that catches inserts into a table, and if the location attribute of the new tuple getting into that table doesn't exist in the database, I need to throw a warning message and insert that new location into another table.
What I have now so far -
CREATE TRIGGER sightTrigger
AFTER INSERT ON SIGHTINGS
FOR EACH ROW
DECLARE
ct INTEGER;
BEGIN
SELECT COUNT(*)
INTO ct
FROM SIGHTINGS
WHERE SIGHTINGS.location <> :NEW.location;
IF ct > 0 THEN
RAISE_APPLICATION_ERROR('WARNING SIGN' || :NEW.location ||' does not exist in the database');
INSERT INTO FEATURES(LOCATION, CLASS, LATITUDE, ...)
VALUES (:NEW.LOCATION, 'UNKNOWN', ...);
END IF;
END;
I'm getting an error, "PLS-00306: wrong number of types of arguments in call to 'RAISE_APP_ERROR'. Could somebody tell me what's wrong? thank you
Try this:
RAISE_APPLICATION_ERROR(
-20001,
'WARNING SIGN' || :NEW.location || 'does not exist in the database'
);
Your RAISE_APPLICATION_ERROR takes two arguments (this is from Oracle docs): where error_number is a negative integer in the range -20000 .. -20999 and message is a character string up to 2048 bytes long.

Resources