具有触发器动态列值的MySQL存储过程审计表插入失败

时间:2018-07-10 06:16:41

标签: mysql

触发:

create trigger audit_po_hd before delete on tra_po_hd 
for each row
BEGIN
DECLARE coumn_nm text;
DECLARE deleted_id text;
SET  @coumn_nm  := ( SELECT  group_concat( DISTINCT column_name) FROM information_schema.columns WHERE table_name='tra_po_hd' );  // get dynamic column

set @deleted_id:= old.trnpurhdid; // get current deleted id

CALL audt_pro(@coumn_nm,@deleted_id); // call stored procedure
END

存储过程:

DELIMITER $$
CREATE PROCEDURE audt_pro(IN coumn_nm text, IN deleted_id text)
BEGIN
DECLARE qry text;
set @coumn_nm :=coumn_nm;
set @deleted_id :=deleted_id;
SET @qry = concat('SELECT  ',  coumn_nm  ,' from tra_po_hd where trnpurhdid = ',deleted_id);
PREPARE stmt FROM @qry;
EXECUTE stmt ;  

insert into audit_dt (hd_id,col_nm,old_val) values (deleted_id,coumn_nm, @qry);
END

我尝试插入获取结果: enter image description here

实际上,我需要使用group_concat()选择查询和old_val这样的结果

old_val列:

  

36 *** 2 *** 2017-07-01 *** 1 *** 196 *** 8535 *** 5000 ***等...

修改后的存储过程

DELIMITER $$
CREATE PROCEDURE audt_pro(IN coumn_nm text, IN deleted_id text)
BEGIN
        DECLARE qry text;
        DECLARE _parent INT;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET @id = NULL;
        set @coumn_nm :=coumn_nm;
        set @deleted_id :=deleted_id;
        set @col :='';
        INSERT INTO audit_hd (date,tbl_nm,tbl_id,type,usr_id,usr_nm)
        SELECT  now(),tbl_nm,deleted_id,'DELETE',b.user_creation_id,b.login_id from mas_uom a join mas_user b on b.user_creation_id = createdby  where  a.uomid =deleted_id;--   SELECT coumn_nm;
        SET @last_id := LAST_INSERT_ID();
        SET @coumn_nm1 :=concat("SELECT  concat_ws(",'"***"',",",  coumn_nm  ,") into @col  from mas_uom   where  uomid = '",deleted_id,"'");
        set @query1 := @coumn_nm1;
        PREPARE stmts FROM @query1;
        EXECUTE stmts;
        set @qry :=concat('insert into audit_dt(hd_id,col_nm,old_val) (select "',@last_id,'","',coumn_nm,'" ,"',@col,'" from mas_uom where  uomid =',deleted_id,' );');
        set @query := @qry;
        PREPARE stmt FROM @query;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        DEALLOCATE PREPARE stmts;

        END

手动运行存储过程得到结果

old_val

1 ***否*** 1 *** 2018-07-13 00:00:00 *** 1 *** 1

但是我由触发器调用时出现错误:存储函数或触发器中不允许动态SQL

如何解决此错误以将条目传递给我的审核表?

0 个答案:

没有答案