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;

最後的語法就是對的瞭。

You May Also Like