/*Changing Default Delimiter from ; to $$ for creating stored procedures.*/
DELIMITER $$
DROP procedure IF EXISTS 'SP_PD_CREATE_EMPLOYEE'$$
CREATE PROCEDURE SP_PD_CREATE_EMPLOYEE()
BEGIN
-- Variable Declaration goes here.
DECLARE V_EMP_CITY VARCHAR(20);
DECLARE V_EMP_ID BIGINT;
/*
(Note: Variables should be declared before handlers and assigning values to variables should come only after handler declarations);
*/
DECLARE exit handler for sqlexception
BEGIN
-- ERROR
ROLLBACK;
END;
DECLARE exit handler for sqlwarning
BEGIN
-- WARNING
ROLLBACK;
END;
START TRANSACTION;
SET V_EMP_CITY = 'CHENNAI';
INSERT INTO table_name (id, name, address) values ('1','Avinash','xpertdeveloper.com');
UPDATE second_table set name="xyz" where id=4;
COMMIT;
COMMIT;
END $$
DELIMITER ; -- Switch to Default Delimiter ; from $$
DECLARE EXIT HANDLER FOR SQLEXCEPTION -- ERROR HANDLING STARTS HERE (CATCH BLOCK)
BEGIN
ROLLBACK;
GET DIAGNOSTICS CONDITION 1
code = RETURNED_SQLSTATE, msg = MESSAGE_TEXT, ERRNO = MYSQL_ERRNO;
SET FORMATTED_ERR_MSG = CONCAT('[SQLSTATE : ',code,'] [MYSQL_ERRNO : ',ERRNO ,'] MESSAGE : ',msg);
/*Log Fail Status; */
INSERT INTO LOG(ERROR_MSG) VALUES(FORMATTED_ERR_MSG) VALUES(FORMATTED_ERR_MSG);
END;
DELIMITER $$
DROP procedure IF EXISTS 'SP_PD_CREATE_EMPLOYEE'$$
CREATE PROCEDURE SP_PD_CREATE_EMPLOYEE()
BEGIN
-- Variable Declaration goes here.
DECLARE V_EMP_CITY VARCHAR(20);
DECLARE V_EMP_ID BIGINT;
/*
(Note: Variables should be declared before handlers and assigning values to variables should come only after handler declarations);
*/
DECLARE exit handler for sqlexception
BEGIN
-- ERROR
ROLLBACK;
END;
DECLARE exit handler for sqlwarning
BEGIN
-- WARNING
ROLLBACK;
END;
START TRANSACTION;
SET V_EMP_CITY = 'CHENNAI';
INSERT INTO table_name (id, name, address) values ('1','Avinash','xpertdeveloper.com');
UPDATE second_table set name="xyz" where id=4;
COMMIT;
COMMIT;
END $$
DELIMITER ; -- Switch to Default Delimiter ; from $$
-- Error Handling - Rollback,Capturing Error messages and log in table.
DECLARE EXIT HANDLER FOR SQLEXCEPTION -- ERROR HANDLING STARTS HERE (CATCH BLOCK)
BEGIN
ROLLBACK;
GET DIAGNOSTICS CONDITION 1
code = RETURNED_SQLSTATE, msg = MESSAGE_TEXT, ERRNO = MYSQL_ERRNO;
SET FORMATTED_ERR_MSG = CONCAT('[SQLSTATE : ',code,'] [MYSQL_ERRNO : ',ERRNO ,'] MESSAGE : ',msg);
/*Log Fail Status; */
INSERT INTO LOG(ERROR_MSG) VALUES(FORMATTED_ERR_MSG) VALUES(FORMATTED_ERR_MSG);
END;