What I have to do is, whenever a STORE_CODE is entered it will check in the db and delete the store code. SO for that, I have written a procedure which is as below
PROCEDURE DELETE_STORE_INFO
(
P_STORE_CODE IN NVARCHAR2
)
AS
BEGIN
UPDATE TBL_RRSOC_STORE_INFO set ISACTIVE = 'N' where STORE_CODE = P_STORE_CODE;
END DELETE_STORE_INFO;
But here what missing is
what if the user enter the wrong store_code and does the operation so what it will do. how to check with that part ?
I guess something for COUNT wont work at this stage. Kindly suggest
You want to use SQL%ROWCOUNT to find out how many rows were affected by the previous SQL statement:
PROCEDURE DELETE_STORE_INFO
(
P_STORE_CODE IN NVARCHAR2
)
AS
BEGIN
UPDATE TBL_RRSOC_STORE_INFO
SET ISACTIVE = 'N'
WHERE STORE_CODE = P_STORE_CODE;
IF SQL%ROWCOUNT = 0 THEN
-- DBMS_OUTPUT.PUT_LINE( 'Store code does not exist.' );
RAISE_APPLICATION_ERROR( -20000, 'Store code does not exist.' );
END IF;
END DELETE_STORE_INFO;
/
You can use DBMS_OUTPUT.PUT_LINE( string ) to output to the SQL console (if you are calling this from an external language like PHP or Java then you will not see the output and you may not see it in the console if you have SET SERVEROUTPUT OFF).
You could also use RAISE_APPLICATION_ERROR( error_code, error_message ) to raise an exception if something invalid happens.
Alternatively you could return a status in an OUT parameter:
PROCEDURE DELETE_STORE_INFO
(
P_STORE_CODE IN NVARCHAR2,
O_STATUS OUT NUMBER
)
AS
BEGIN
UPDATE TBL_RRSOC_STORE_INFO
SET ISACTIVE = 'N'
WHERE STORE_CODE = P_STORE_CODE;
IF SQL%ROWCOUNT = 0 THEN
o_status := 0;
ELSE
o_status := 1;
END IF;
END DELETE_STORE_INFO;
/
Generally contract for your procedure is: caller gives some store_code and procedure guarantee that there is no active store with such code. What if caller gives the wrong store_code? It means there is no such store, so contract is accomplished. You should do nothing, no more :)
But if you wish to check whether update found the record or not, you can add something like
if sql%notfound then
dbms_output.put_line('There is no such store!');
end if;
immediately after update statement.
Especially for MT: just check simple script
create table t$(id integer);
insert into t$ values(1);
set serveroutput on
begin
update t$ set id = 2 where id = 1;
if sql%notfound
then dbms_output.put_line('#1: not found');
else dbms_output.put_line('#1: found');
end if;
update t$ set id = 4 where id = 3;
if sql%found then
dbms_output.put_line('#2: found');
else dbms_output.put_line('#2: not found');
end if;
end;
/
drop table t$;
My results are
Connected to Oracle Database 12c Enterprise Edition Release 12.1.0.2.0
#1: found
#2: not found
PL/SQL procedure successfully completed
There are something missunderstand in your request: you said you want to delete it but in the code, you just updated the store as incative.
Here is the proceure with both situation. You choose the right one:
CREATE OR REPLACE PROCEDURE DELETE_STORE_INFO (P_STORE_CODE IN NVARCHAR2) AS
n_count number;
BEGIN
select count(1) INTO n_count from TBL_RRSOC_STORE_INFO where STORE_CODE = p_store_code;
if n_count > 0 then
UPDATE TBL_RRSOC_STORE_INFO set ISACTIVE = 'N' where STORE_CODE = P_STORE_CODE;
-- or for deletion
-- DELETE TBL_RRSOC_STORE_INFO set ISACTIVE = 'N' where STORE_CODE = P_STORE_CODE;
else
DBMS_OUTPUT.PUT_LINE('the required store was not found');
end if;
END DELETE_STORE_INFO;
Related
I am not sure how to resolve the above error I am getting. How should I declare it? I created the procedure below to allow a passenger to buy a metro card and add it to an existing account. Input includes account id, initial balance
SET SERVEROUTPUT ON
-- procedure to buy new metro, output error if account already exists.
CREATE OR REPLACE PROCEDURE NewCard (
input_Account_ID IN varchar,
input_Balance IN varchar,
input_age IN varchar
)
IS
acct varchar(255);
-- compare the input account id to see if it exists in the table
CURSOR S1 is SELECT Account_id from Rider_Account where ACCOUNT_ID = input_Account_ID;
BEGIN
--THIS MEANS THE RECORD EXISTS
open S1;
LOOP
FETCH S1 into acct;
EXIT WHEN S1%notfound;
END LOOP;
-- go through the records
IF (acct = input_Account_ID) THEN
Dbms_ouput.Put_line('Account exists');
ELSE
BEGIN
INSERT into Metro_Card(Card_ID, Account_ID, Balance) VALUES(Card_Sequence.NEXTVAL,input_Account_ID, input_Balance);
INSERT into rider_account(Age) VALUES (input_age);
END;
END IF;
IF (input_age <= 12) THEN
UPDATE Metro_Card
SET Discount_type = 2
Where Metro_Card.Account_ID = input_Account_ID;
ELSIF (input_age >= 65) THEN
UPDATE Metro_Card
SET Discount_type = 3
Where Metro_Card.Account_ID = input_Account_ID;
ELSE
UPDATE Metro_Card
SET Discount_type = 1
Where Metro_Card.Account_ID = input_Account_ID;
END IF;
END;
It is not
Dbms_ouput.Put_line('Account exists');
but
Dbms_ouTput.Put_line('Account exists');
-
^
missing "T"
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.
I want to update a table but I want to check if the record exist. If not then throw an exception. In the C# application I pass the parameters and execute the command by the following.
procedure usp_update_example
(
p_id in mydb.member.idn_member%type,
p_idn_person in mydb.member.idn_person%type,
p_ind_rep in mydb.member.ind_rep%type
)
as
v_exist pls_integer := 0;
v_step varchar2(250);
v_exception_not_exist exception;
begin
v_step := 'Check for record ' || p_id;
select count(1)
into v_exist
from mydb.member
where idn_member = p_id;
if v_exist = 0 then
raise v_exception_not_exist;
end if;
if (v_exist > 0) then
v_step := 'Update table :' || p_id;
update mydb.member
set
idn_person = p_idn_person,
ind_rep = p_ind_rep
where idn_member = p_id;
end if;
exception
when v_exception_not_exist then
Raise_application_error(-20001, 'Not exist');
end usp_update_example;
However even my condition is right, I do have the record existing in the table. I always get Not exist exception. If I don't use if v_exist = 0 and use WHEN NO_DATA_FOUND THEN. Then everything is fine.
I am not sure where is wrong.
Your code seems to be fine. Looks like this issue is related to some uncommitted data - you see the record in the session where you inserted it and you don't see it in C# session since the record is not committed yet. Hence, C# session generates exception.
What I would suggest re the procedure code is to make it more compact.
Something like the following:
...
begin
update mydb.member
set idn_person = p_idn_person,
ind_rep = p_ind_rep
where idn_member = p_id;
if SQL%ROWCOUNT = 0 then
raise_application_error(-20001,'Not exist');
end if;
end;
Please see my code below. If the parameter p_cust_id is not in the column cust_id I want "0" to be printed out (which means not logged in). If it is in cust_id I want oracle to continue the second part of the code (the part below the empty row).
I have tried to solve this by inserting the values of column cust_id in a cursor and then inserting it in the variable v_cust_id. Perhaps this results in unnecessarily much code?
My problem is that the program does not seem to run the second part even if p_cust_id is in cust_id. It just prints out "0" even though the customer ID and the password are correct.
Before I added the cursor the program worked as it was supposed to, unless the parameter p_cust_id didn't match any value in the cust_id column. If this was the case nothing was printed out.
create or replace function log_in(
p_cust_id in customer.cust_id%type,
p_passwd in customer.passwd%type)
return varchar2
as
cursor c_cust_id is select cust_id from customer;
v_cust_id customer.cust_id%type;
v_passwd customer.passwd%type;
v_logged_in number(1);
v_not_logged_in number(1);
begin
v_logged_in := 1;
v_not_logged_in := 0;
if not c_cust_id%isopen then
open c_cust_id;
end if;
loop
fetch c_cust_id
into v_cust_id;
exit when c_cust_id%notfound;
end loop;
if p_cust_id not in(v_cust_id) then
return v_not_logged_in;
end if;
close c_cust_id;
select passwd
into v_passwd
from customer
where cust_id = p_cust_id;
if v_passwd = p_passwd then
return v_logged_in;
else
return v_not_logged_in;
end if;
end;
I could see, you don't need a cursor at all, to check if the cust_id is in the table. Just search for the cust_id in the table, and attempt to fetch the password. If it exists, you get the value, and NO_DATA_FOUND exception otherwise which means not logged in.
BEGIN
select passwd
into v_passwd
from customer
where cust_id = p_cust_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
return v_not_logged_in;
END;
Full code will be:
create or replace function log_in(
p_cust_id in customer.cust_id%type,
p_passwd in customer.passwd%type)
return varchar2
as
v_cust_id customer.cust_id%type;
v_passwd customer.passwd%type;
v_logged_in number(1);
v_not_logged_in number(1);
begin
v_logged_in := 1;
v_not_logged_in := 0;
BEGIN
select passwd
into v_passwd
from customer
where cust_id = p_cust_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
return v_not_logged_in;
END;
if v_passwd = p_passwd then
return v_logged_in;
else
return v_not_logged_in;
end if;
end;
I would like to create a trigger that prevents a student from enrolling into a new module if he has any outstanding bills.
studID studNRIC paymentStatus
-------------------------------------
200 F7654672F Non Payment
it would reject the following statement:
INSERT INTO student(studID, studNRIC, paymentStatus)
VALUES (201, 'F7654672F', 'Good');
I've came out with the following trigger but I'm still able to insert a new student.
set define off;
CREATE OR REPLACE TRIGGER reject_new_account
AFTER INSERT OR UPDATE ON Student
FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
totover NUMBER(3);
BEGIN
SELECT COUNT (*)
INTO totover
FROM Student
WHERE :NEW.nric = student.nric
AND :NEW.paymentStatus = 'Non Payment';
IF totover > 0 THEN
RAISE_APPLICATION_ERROR ( -20002,
'Student' || :NEW.nric ||
' has outstanding bills' );
END IF;
END;
/
there's seems to be a problem with line 13 AND :NEW.paymentStatus = 'Non Payment';
so how do I go about doing this?
table structure
CREATE TABLE Student(
studID INTEGER NOT NULL,
firstName CHAR(25) NULL,
lastName CHAR(25) NULL,
NRIC CHAR(9) NOT NULL,
paymentStatus CHAR(25) Default 'Good',
CONSTRAINT stud_Pkey PRIMARY KEY (studID),
CONSTRAINT studPaymentStatus_type CHECK (PaymentStatus IN ('Late Payment', 'Non Payment', 'Good'))
);
There are a couple of issues with this trigger.
First if you want to prevent an INSERT you need to use a BEFORE trigger. An AFTER trigger will fire after the insert has successfully completed, by which point it is too late to stop the insert.
Secondly, I'm unsure about what you are trying to achieve with your SQL statement. Since the trigger is attached to the customer table you don't need to do a select on the customer table to access the record data. You can just do:
IF :NEW.badstatus = 'Non Payment'
THEN
RAISE_APPLICATION_ERROR ( -20002,
'Employee ' || :NEW.nric ||
' already has 5 readings' );
END IF;
You probably don't want to check if the new record has a bad status, you want to check if the existing customer records have a bad status. As James mentioned, a BEFORE trigger probably makes more sense, but that depends on what you are trying to do, whether the insert gets rollback or not by the caller, etc.
CREATE OR REPLACE TRIGGER reject_new_account
AFTER INSERT OR UPDATE ON Customer
FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
totover NUMBER(3);
BEGIN
SELECT COUNT (*)
INTO totover
FROM Customer c
WHERE c.nric = :NEW.nric
AND c.badstatus = 'Non Payment';
IF totover > 0 THEN
RAISE_APPLICATION_ERROR ( -20002,
'Employee ' || :NEW.nric ||
' already has 5 readings' );
END IF;
END;
/
I've removed the PRAGMA AUTONOMOUS_TRANSACTION; for you and replace it with an exception to handle the issue, can you try if it works.
set define off;
CREATE OR REPLACE TRIGGER reject_new_account
BEFORE INSERT OR UPDATE ON CUSTOMER
FOR EACH ROW
DECLARE
totover CHAR(100);
BEGIN
SELECT distinct badStatus
INTO totover
FROM customer
WHERE :NEW.nric = CUSTOMER.nric;
IF totover = 'Non Payment' THEN
RAISE_APPLICATION_ERROR ( -20003,
'Customer ' || :NEW.firstName||''||:NEW.lastName ||
' cannot create new account due to bad payment' );
END IF;
EXCEPTION
WHEN NO_DATA_FOUND
THEN DBMS_OUTPUT.PUT_LINE(TO_CHAR(SQLERRM(-20299)));
END;
/
As I assume you have discovered, you cannot select from the same table that a row-level trigger is defined against; it causes a table mutating exception. You have attempted to get round this by adding the autonomous transaction pragma. Unfortunately, although this works, it is just covering up your mistake in methodology.
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 = 1) THEN
raise_application_error(-20001, 'dbms_lock.request Timeout');
ELSIF (l_return = 2) THEN
raise_application_error(-20001, 'dbms_lock.request Deadlock');
ELSIF (l_return = 3) THEN
raise_application_error(-20001, 'dbms_lock.request Parameter Error');
ELSIF (l_return = 5) THEN
raise_application_error(-20001, 'dbms_lock.request Illegal Lock Handle');
ELSIF (l_return not in (0,4)) THEN
raise_application_error(-20001, 'dbms_lock.request Unknown 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 reject_new_account
FOR INSERT OR UPDATE ON student
COMPOUND TRIGGER
-- Table to hold identifiers of inserted/updated students
g_studIDs sys.odcinumberlist;
BEFORE STATEMENT
IS
BEGIN
-- Reset the internal student table
g_studIDs := g_studIDs();
END BEFORE STATEMENT;
AFTER EACH ROW
IS
BEGIN
-- Store the inserted/updated students; the payment status may be updated
-- without checking the constraint
IF ( INSERTING
OR ( UPDATING
AND ( :new.studID <> :old.studID
OR :new.NRIC <> :old.NRIC)))
THEN
g_studIDs.EXTEND;
g_studIDs(g_studIDs.LAST) := :new.studID;
END IF;
END AFTER EACH ROW;
AFTER STATEMENT
IS
CURSOR csr_students
IS
SELECT sdt.studID
, sdt.NRIC
FROM TABLE(g_studIDs) sid
INNER JOIN student sdt
ON (sdt.studID = sid.column_value)
ORDER BY sdt.NRIC;
CURSOR csr_constraint_violations
(p_studID student.studID%TYPE
,p_NRIC student.studNRIC%TYPE)
IS
SELECT NULL
FROM student sdt
WHERE sdt.NRIC = p_NRIC
AND sdt.paymentStatus = 'Bad Payment'
AND sdt.studID <> p_studID;
r_constraint_violation csr_constraint_violations%ROWTYPE;
BEGIN
-- Check if for any inserted/updated student there exists another record for
-- the same NRIC with a Bad Payment status. Serialise the constraint for each
-- NRIC so concurrent transactions do not affect each other
FOR r_student IN csr_students LOOP
request_lock('REJECT_NEW_ACCOUNT_' || r_student.NRIC);
OPEN csr_constraint_violations(r_student.studID, r_student.NRIC);
FETCH csr_constraint_violations INTO r_constraint_violation;
IF csr_constraint_violations%FOUND THEN
CLOSE csr_constraint_violations;
raise_application_error(-20001, 'Student ' || r_student.NRIC || ' has Bad Payment status');
ELSE
CLOSE csr_constraint_violations;
END IF;
END LOOP;
END AFTER STATEMENT;
END;