使用触发器之前,首先要看服务器是否配置了,不然会报如下错误
解决如下
记得要重启下数据库才会生效
log_bin_trust_function_creators=1
更新
begin
if (new.qianbao-old.qianbao>0) then
set new.kuangchi=old.kuangchi+(new.qianbao-old.qianbao)*5;
set new.qianbao=old.qianbao;
INSERT INTO ds_kuangchi ( kuangchi, username,time) VALUES ( old.kuangchi+(new.qianbao-old.qianbao)*5, new.username,unix_timestamp(now()));
end if;
end
定义变量
begin
DECLARE x int (11);
set x=0;
end
定义变量查询
begin
DECLARE x varchar(255);
set x=(select id from cd_xianyoukucuns where id=1);
set new.yuanliaomingcheng_id=x;
end
禁止插入 提示框
begin
DECLARE x int (11);
set x=1;
if(x>0) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "your error text";
end if;
END
注意mysql触发器中的before和after的区别:
before:(insert、update)可以对new进行修改,
after:不能对new进行修改,两者都不能修改old数据。
对于INSERT语句, 只有NEW是合法的;
对于DELETE语句,只有OLD才合法;
对于UPDATE语句,NEW、OLD可以同时使用。
BEGIN
DECLARE p_gets,a_gets,u_gets DECIMAL (10,2);
set p_gets=new.p_get;
set a_gets=new.a_get;
set u_gets=new.u_get;
IF (new.auto>0) THEN
UPDATE wallets SET income_total=income_total+p_gets where uid=1 and type=2;
UPDATE wallets SET income_total=income_total+a_gets where uid=new.a_id and type=2;
UPDATE wallets SET income_total=income_total+u_gets where uid=new.u_id and type=1;
END IF;
END