记录一次mysql存储过程编写的例子(异常处理+事务回滚)

DELIMITER $$

USE `ebs`$$

DROP PROCEDURE IF EXISTS `pro_ebs_sap_t500p_update`$$

CREATE DEFINER=`ebs`@`10%` PROCEDURE `pro_ebs_sap_t500p_update`(OUT `result_status` INTEGER,OUT `result_quantity` INTEGER,OUT `result_msg` TEXT,OUT `result_log_id` INTEGER)
BEGIN
      -- 声明变量
      DECLARE THIS_MOMENT DATETIME DEFAULT SYSDATE();
      DECLARE TI_LATEST_SERNO VARCHAR(20);
      DECLARE TT_LATEST_SERNO VARCHAR(20);
      DECLARE quantity INTEGER DEFAULT 0;
      DECLARE t_succ INTEGER DEFAULT 1;
      DECLARE msg TEXT DEFAULT 'ok';
      -- 异常捕获
      DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN get diagnostics CONDITION 1 msg = message_text; SET t_succ = 0; END ;
      
      -- 开启事务
      START TRANSACTION;
      
      -- 业务处理
      SELECT SERNO INTO TI_LATEST_SERNO FROM ti_ebs_sap_t500p ORDER BY ETL_TM DESC LIMIT 1;
      SELECT SERNO INTO TT_LATEST_SERNO FROM tt_ebs_sap_t500p ORDER BY SYN_TM DESC LIMIT 1;
      IF 
			TT_LATEST_SERNO IS NULL OR TI_LATEST_SERNO != TT_LATEST_SERNO
      THEN 
			DELETE FROM tt_ebs_sap_t500p;
			UPDATE ti_ebs_sap_t500p SET SYN=1,SYN_TM=THIS_MOMENT WHERE SERNO = TI_LATEST_SERNO;
			INSERT INTO tt_ebs_sap_t500p(SERNO,PERSA,MOLGA,BUKRS,NAME1,NAME2,STRAS,PFACH,PSTLZ,ORT01,LAND1,REGIO,COUNC,CITYC,ADRNR,SYN_TM) 
				SELECT SERNO,PERSA,MOLGA,BUKRS,NAME1,NAME2,STRAS,PFACH,PSTLZ,ORT01,LAND1,REGIO,COUNC,CITYC,ADRNR,SYN_TM 
					FROM ti_ebs_sap_t500p 
					WHERE SERNO = TI_LATEST_SERNO;
			SELECT COUNT(1) INTO quantity FROM tt_ebs_sap_t500p;
      END IF;
      
      -- 事务提交或回滚
      IF
			t_succ = 0
      THEN
			ROLLBACK;
      ELSE
			COMMIT;
      END IF;
      
      -- 记录日志
      INSERT INTO `tl_ebs_pro_exec_log` (`quantity`,`ti_table_name`,`tt_table_name`,`status`,`message`,`ti_serno`,`tt_serno`) 
			VALUES(quantity,'ti_ebs_sap_t500p','tt_ebs_sap_t500p',t_succ,msg,TI_LATEST_SERNO,TT_LATEST_SERNO);
      
      -- 返回信息
      SELECT t_succ INTO result_status;
      SELECT msg INTO result_msg;
      SELECT quantity INTO result_quantity;
      SELECT LAST_INSERT_ID() INTO result_log_id;
	
END$$

DELIMITER ;

CALL pro_ebs_sap_t500p_update(@A,@B,@C,@D);
SELECT @A,@B,@C,@D;

 

你可能感兴趣的:(mysql)