mysql 触发器使用

//数据新增时校验 ,在插入的时候控制

A表新增数据的时候,校验数据是否存在。存在不插入

----创建触发器
CREATE 
TRIGGER  befor_insert_suppur_bargain_trigger  
BEFORE INSERT ON  suppur_bargain 
FOR EACH ROW
 BEGIN   
        IF EXISTS (SELECT bargain_id FROM  suppur_bargain where procurecatalog_id=NEW.procurecatalog_id and hospital_id=NEW.hospital_id and NEW.bargain_status in(0,2,3))   THEN             
            SIGNAL SQLSTATE '45000' SET message_text = '数据重复'; 
        END IF; 
end ;


--查看
SHOW TRIGGERS; 
--删除
DROP TRIGGER befor_insert_suppur_bargain_trigger;

字段变更的时候触发

A表字段变更时候,变更B表状态,同时记录B的操作记录表。

CREATE TRIGGER after_update_suppur_procurecatalog_trigger
AFTER UPDATE ON suppur_procurecatalog  FOR EACH ROW 
BEGIN
  if(new.purchase_price!=old.purchase_price) then
	 -- 新增记录表,注意要把记录表操作放在前面。否则修改了B表后,过滤条件失效	 			
			INSERT INTO purchase_information_confirmation_log 
			( config_id, org_type, state, cycle, start_time, end_time, purchase_price, remark, add_time ) 
					SELECT
					a.id,
					2,
					9,
					a.cycle,
					a.start_time,
					a.end_time,
					new.purchase_price,
					'价格变更',
					NOW() 
			FROM
				purchase_information_confirmation a
			WHERE
			a.procurecatalog_id=new.procurecatalog_id
			AND a.state IN ( 3, 4 ) 
			AND a.start_time_pre <= NOW() AND a.end_time >= NOW();
	 -- 修改XXX表状态
	 update purchase_information_confirmation
	 SET state=8, last_update_time=NOW()
		where state in(3,4) 
		and  start_time_pre<=now()
		AND end_time>=now()
		and procurecatalog_id=new.procurecatalog_id;			
	  END IF;
END;

猜你喜欢

转载自blog.csdn.net/qq_37570710/article/details/126546718