Search code examples
plsqltriggersplsqldeveloperdatatrigger

How to write a pl/sql program to not allow transaction on Sundays using trigger?


I have a table named emp1

Create table emp1
(
 Emp_no number(3),
 Name varchar(10),
 Salary number(9,2),
 Dept_no number(3)
);

My trigger is

create or replace trigger tri1
before insert on emp1
for each row
begin
   if to_char(sysdate,'day')='sunday' then
       dbms_output.put_line('You cannot access');
   End if;
End;

After executing this trigger, I insert below statement

insert into emp1(Name, Salary, Dept_no) values ('abc',12000,101);

Every time I insert its always getting inserted.

I have also tried using exception

create or replace trigger tri1 
before insert on emp1 
for each row 
declare
     weekday_error exception;
begin 
if to_char(sysdate,'day')='sunday' then
raise weekday_error;
end if; 
Exception
  when weekday_error then
     dbms_output.put_line('You cannot access');
End;

With this method also records are always getting inserted.

  create or replace trigger tri1 
    before insert on emp1 
    for each row 

    begin 
    if to_char(sysdate,'Day')='Sunday' then
    raise_application_error(-20000,'Cannot do transaction on Sunday');
    End if; 

End;

Solution

  • There is just one tiny problem with your trigger. TO_CHAR(sysdate,'day') actually returns 9 characters.

    like MONDAY that is 6 characters and then 3 Space characters. This is because of WEDNESDAY which has 9 characters.

    Your trigger just needs the trim function

    create trigger trig1 before insert on emp1
    for each row
    begin
        if trim(to_char(sysdate, 'day')) = 'sunday' then
            raise_application_error(-20000,'ikidyounot, today was - ' || to_char(sysdate, 'day'));
        end if;
    end;
    /