在这个我有2个表我需要一行中的旧值和一行中的新值

时间:2017-07-07 10:01:05

标签: mysql

表1

  

create table emp(id int,emp_id int,       name varchar(30),email varchar(50),mobile_no int,comments varchar(50));

表2

  

创建表历史记录(id int,oldvalue varchar(50),newvalue   VARCHAR(50));

插入第一个表格

insert into emp(emp_id,name,email,mobile_no,comments) 
 values(1, 'gobi','gobinath@gmail.com',9944,'good');

TRIGGER

  

CREATE TRIGGER tri

BEFORE UPDATE ON emp

FOR EACH ROW 

BEGIN

    INSERT INTO history

    SET id = '1',
     oldvalue = OLD.name,
     newvalue = NEW.name;
     INSERT INTO history

     SET id = '2',
      oldvalue = OLD.email,
     newvalue = NEW.email;
     INSERT INTO history

     SET id = '3',
     oldvalue = OLD.mobile_no,
     newvalue = NEW.mobile_no;
        END;
UPDATE emp 

SET 
    name = 'ashok',
 email = 'ashok@gmail.com',
mobile_no = '929292'
WHERE
    emp_id = 1;

上面的触发器工作正常,但我需要填写2行,但此触发器的输出是多行创建。

1 个答案:

答案 0 :(得分:0)

create table emp(id int auto_increment,emp_id int,
name varchar(30),email varchar(50),mobile_no int,comments varchar(50),primary key(id));

create table history(id int,oldvalue varchar(50),newvalue varchar(50));




insert into emp(emp_id,name,email,mobile_no,comments) 
 values(1, 'gobi','gobinath@gmail.com',9944,'good');



CREATE TRIGGER tri 
    AFTER UPDATE ON emp
    FOR EACH ROW 
BEGIN

DECLARE ooldvalue TEXT DEFAULT '';
    DECLARE nnewvalue TEXT DEFAULT '';

IF((OLD.name!=NEW.name) OR (OLD.email!=NEW.email) OR (OLD.mobile_no!=NEW.mobile_no))THEN
SET ooldvalue = CONCAT(ooldvalue,'id=', OLD.id,','); 

    END IF;

IF(OLD.name!=NEW.name) THEN 
        SET ooldvalue=CONCAT(ooldvalue,'name=',OLD.name,',');
        SET nnewvalue = CONCAT(nnewvalue,'name=',NEW.name,',');
    END IF;

IF(OLD.email!=NEW.email) THEN 
        SET ooldvalue=CONCAT(ooldvalue,'email=',OLD.email,',');
        SET nnewvalue = CONCAT(nnewvalue,'email=',NEW.email,',');
    END IF;

IF(OLD.mobile_no!=NEW.mobile_no) THEN 
        SET ooldvalue=CONCAT(ooldvalue,'mobile_no=',OLD.mobile_no,',');
        SET nnewvalue = CONCAT(nnewvalue,'mobile_no=',NEW.mobile_no,',');
    END IF;

IF(ooldvalue!='' AND nnewvalue!='') THEN

        IF(ooldvalue!=nnewvalue)THEN
            SET ooldvalue = SUBSTRING(ooldvalue,1,CHAR_LENGTH(ooldvalue)-1);
            SET nnewvalue = SUBSTRING(nnewvalue,1,CHAR_LENGTH(nnewvalue)-1);
            INSERT INTO history(oldvalue,newvalue) values (ooldvalue,nnewvalue);
         END IF; 
        END IF;
      END; 

从emp

中选择*

从历史中选择*

UPDATE emp 
SET 
    name = 'ashok', email = 'ashok@gmail.com',mobile_no = '929292'
where
    emp_id = 1;