How to implement Roll Back Transaction and Error Message in MYSQL

血红的双手。 提交于 2021-02-11 13:53:59

问题


I Have sample procedure .

CREATE PROCEDURE `sample_procedure ` 
(
IN IDIn bigint(20),
IN MainIDIn bigint(20),
IN NameIn  varchar(20)
)
 READS SQL DATA
    DETERMINISTIC
BEGIN
INSERT INTO tbl_DEPT
(
ID,
Name)
Select 1,'Mohan';

IF NOT EXISTS (SELECT ID FROM tbl_emp  te  WHERE te.ID = IDIn) THEN 
INSERT INTO tbl_emp
(
MainID,
Name) 
VALUES (MainIDIn,
        NameIn);
ELSE 
IF  EXISTS (SELECT ID FROM tbl_emp  te  WHERE te.ID = IDIn) THEN 
  UPDATE tbl_emp  
  set
    MainID =MainIDIn,
    name = NameIn
  WHERE te.ID= IDIn;
  END IF;
  END IF;
END

Call sample_procedure(1,2,Sampl123)

I'm just sending some irrelevant Data into the Procedure so that procedure gets failed . But how we need to implement roll back means it should come to the starting state with out Inserting Records into the tbl_DEPT also.

IN T-SQL we will have

BEGIN
    SET NOCOUNT ON
    BEGIN TRANSACTION
    BEGIN TRY
        SET @OUT = "success";
        COMMIT TRANSACTION
    END TRY

    BEGIN CATCH
        set @out = 'not success';
        ROLLBACK TRANSACTION
    END CATCH
END

this kind of TRY CATCH blocks and to capture Error

 "ERROR_NUMBER() AS ErrorNumber,
    ERROR_SEVERITY() AS ErrorSeverity"

In the same way in MYSQL I'm looking for TRY CATCH and ROLL BACK Mechanism .

IF Procedure fails it should ROLL BACK and Not to load in any of the table .

Can any one Suggest me in MYSQL.


回答1:


Mysql does not use try/catch. If uses handlers, e.g. the EXIT handler that will terminate the execution of the SP:

DECLARE EXIT HANDLER FOR SQLEXCEPTION 
BEGIN 
    ROLLBACK;
    -- other logic
END;

There are other type of handlers as well.



来源:https://stackoverflow.com/questions/61481328/how-to-implement-roll-back-transaction-and-error-message-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!