User27854
User27854

Reputation: 884

Mysql problems with Triggers

I have created two tables customerbkp (customer backup) and another table called customer. my intention is to copy all the modifications made in the customer table..

but the code does not compile when I use

delimiter //
create trigger custtrig
before  insert or update or delete on customer
for each row
//statements

I tried few variants of that frustrated with that I am creating individual triggers , the below code seems syntatically correct but it enters only null into the back up table. Could any one explain me why I am getting this result (i.e null ),Is there any way that I could record all the changes in my backup table

create table customerbkp(cid int, cname varchar(25), cemail varchar(25), phone int, operation varchar(10));

create table customer(cid int, cname varchar(25), cemail varchar(25), phone int);

delimiter //
create trigger custtrig
before  insert on customer
for each row
begin
insert into customerbkp(cid) values (cid);
end;
//

delimiter;

insert into customer values(101,'cust1','[email protected]',1111);

Upvotes: 0

Views: 787

Answers (1)

Vatev
Vatev

Reputation: 7590

MySQL does not support insert or update or delete. You need to create 3 separate triggers.

Use AFTER xxx instead of BEFORE xxx triggers, because otherwise you won't have the values for the auto-increment fields (and maybe some others).

You are inserting a row with a value for cid only. You should insert it with all the values:

...
begin
INSERT INTO customerbkp(cid,cname,cemail,phone,operation) 
    VALUES (NEW.cid, NEW.cname, NEW.cemail, NEW.phone, 'insert');
end;
...

Change 'insert' to an appropriate value for each trigger. Also you will need to use OLD instead of NEW in the AFTER DELETE trigger (or maybe have NULL's...).

Upvotes: 1

Related Questions