问题
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