Reputation: 35
I have two tables--
create table mobile
(
id int,
m_name varchar(20),
purchase_date datetime
)
insert into mobile values('1','Samsung corby','12-JAN-12');
insert into mobile values('2','Nokia E5','15-MAR-12');
insert into mobile values('3','Sony Talk','10-FEB-12');
create table location
(
id int,
l_name varchar(20)
)
insert into location values(1,'London');
insert into location values(2,'Washington');
insert into location values(3,'Mexico');
I want to create a trigger which will ensure that sony talk mobile which is in mexico can not be purchased on December.That means whenever I try to insert data in mobile table with ID as 3 and purchase_date as December, the trigger should stop it and give appropriate message.
My code for this is --
create or replace trigger trg1
before insert or update
on mobile
for each row
declare
var1 number(4);
begin
select id into var1 from location where l_name='Mexico';
IF (:new.id = var1 and to_char(:new.purchase_date, 'MONTH') = 'DECEMBER') THEN
raise_application_error( -20001, 'THIS mobile CAN NOT BE PURCHASED NOW.');
END IF;
end;
The trigger was created, but when i try to insert this data using this code--
insert into mobile values('3','Sony Talk','10-JAN-11');
The trigger fires but gives an error --
ORA-04098: trigger 'OPS$0924769.TRG1' is invalid and failed re-validation
and my if code is also not working properly--
IF (:new.id = var1 and to_char(:new.purchase_date, 'MONTH') = 'DECEMBER') THEN
raise_application_error( -20001, 'THIS mobile CAN NOT BE PURCHASED NOW.');
END IF;
its not checking for both id and purchase_date. I gave purchase_date as JAN , so in this case the trigger should not fire. I am confused.
Upvotes: 1
Views: 9325
Reputation: 231671
show errors
after creating the trigger, SQL*Plus will display the syntax errors to you.DATETIME
data type. The data type of the purchase_date
column in mobile
would need to be a DATE
.mobile
tableTO_CHAR
with a format mask of MONTH
, the results will be right-padded with spaces to the length of the longest month (9 characters). Since DECEMBER
only has 8 characters, your condition is never going to evaluate to TRUE
. You would need to either TRIM
the output or to use the fmMONTH
format mask which does not pad the output with spaces. Something like
create or replace trigger trg1
before insert or update
on mobile
for each row
declare
var1 number(4);
begin
select id into var1 from location where l_name='Mexico';
IF (:new.id = var1 and to_char(:new.purchase_date, 'fmMONTH') = 'DECEMBER') THEN
raise_application_error( -20001, 'THIS mobile CAN NOT BE PURCHASED NOW.');
END IF;
end;
would be more likely what you're looking for. But that doesn't explain why your trigger is getting compilation errors.
Upvotes: 7