mysql触发器语法的一个实例
我要实现的功能是:在更新一个表时,从三个表中查询记录并插入到另外一个表中,下面是我写触发器的过程:
第一次写的触发器如下:
CREATE TRIGGER istmingxi
AFTER UPDATE ON sys_shenbao FOR EACH ROW BEGIN
SELECT @kid:=jl.kid,@gonghao:=shen.gonghao,@vuid:=jl.vuid,@zhibiao:=ct.leibie,
@citiao:=ct.bianhao,@fenshu:=ct.fenshu,@bumen:=zl.bumen,@ctime:=shen.verifytime
FROM sys_shenbao shen
INNER JOIN sys_shenbjl jl ON jl.d = shen.sid
INNER JOIN sys_citiao ct ON ct.bianhao = shen.ctbh
INNER JOIN sys_jibzl zl ON zl.gonghao = shen.gonghao
WHERE shen.sid = new.sid;
if fenshu > 0 then
set @jiafen = fenshu;
set @jianfen = 0;
else
set @jiafen = 0;
set @jianfen = fenshu;
end if;
INSERT INTO sys_mingxi(`kid`,`gonghao`,`vuid`,`zhibiao`,`bumen`,`jiafen`,`jianfen`,`yue`,`ctime`)
VALUES(kid,gonghao,vuid,zhibiao,citiao,bumen,jiafen,jianfen,0,ctime);
END;
生成上面触发器时报错:Not allowed to return a result set from a trigger;原因是trigger 中不允许返回select出来的结果集,所以 “select @kid:=jl.kid....”部分改变成另一种写法,如下
CREATE TRIGGER istmingxi
AFTER UPDATE ON sys_shenbao FOR EACH ROW BEGIN
SELECT jl.skid into @kid, shen.gonghao into @gonghao,jl.vuid into @vuid,ct.leibie into @zhibiao,
ct.bianhao into @citiao,ct.fenshu into @fenshu,zl.bumen into @bumen,shen.verifytime into @ctime
FROM sys_shenbao shen
INNER JOIN sys_shenbjl jl ON jl.id = shen.sid
INNER JOIN sys_citiao ct ON ct.bianhao = shen.ctbh
INNER JOIN sys_jibzl zl ON zl.gonghao = shen.gonghao
WHERE shen.sid = new.sid;
if fenshu > 0 then
set @jiafen = fenshu;
set @jianfen = 0;
else
set @jiafen = 0;
set @jianfen = fenshu;
end if;
INSERT INTO sys_mingxi(`kid`,`gonghao`,`vuid`,`zhibiao`,`bumen`,`jiafen`,`jianfen`,`yue`,`ctime`)
VALUES(kid,gonghao,vuid,zhibiao,citiao,bumen,jiafen,jianfen,0,ctime);
END;
此时还是会报错:SQL 错误 [1327] [42000]: Undeclared variable: shen; Undeclared variable: shen;原因是“select jl.skic into @kid...”部门的select语句的语法还是不对。
原因是:欲想通过一个SELECT语句对多个变量赋值,请采用以下语句形式:SELECT id,name INTO @v1,@v2 FROM ...
所以最终我改成了如下的方式:
CREATE TRIGGER istmingxi
AFTER UPDATE ON sys_shenbao FOR EACH ROW BEGIN
SELECT jl.skid,shen.gonghao,jl.vuid,ct.leibie,ct.bianhao,ct.fenshu,zl.bumen,shen.verifytime
INTO @kid,@gonghao,@vuid,@zhibiao,@citiao,@fenshu,@bumen,@ctime
FROM sys_shenbao shen
INNER JOIN sys_shenbjl jl ON jl.id = shen.sid
INNER JOIN sys_citiao ct ON ct.bianhao = shen.ctbh
INNER JOIN sys_jibzl zl ON zl.gonghao = shen.gonghao
WHERE shen.sid = new.sid;
if fenshu > 0 then
set @jiafen = fenshu;
set @jianfen = 0;
else
set @jiafen = 0;
set @jianfen = fenshu;
end if;
INSERT INTO sys_mingxi(`kid`,`gonghao`,`vuid`,`zhibiao`,`bumen`,`jiafen`,`jianfen`,`yue`,`ctime`)
VALUES(kid,gonghao,vuid,zhibiao,citiao,bumen,jiafen,jianfen,0,ctime);
END;
最后的语法就是对的了。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。