表关联形式为:PetAge->PetsonPet->Person.
代码如下:
DROP PROCEDURE IF EXISTS delatePerson;
CREATE PROCEDURE delatePerson(in personId INT)
BEGIN
DECLARE petId INT;
DECLARE petAgeId INT;
DECLARE t_error INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET t_error=1;
SELECT id INTO petId FROM personpet pp WHERE pp.id=personId;
SELECT id INTO petAgeId FROM petage pa WHERE pa.id=petId;
START TRANSACTION;
DELETE FROM petage WHERE petage.id=petAgeId;
DELETE FROM personpet WHERE personpet.id=petId;
DELETE FROM person WHERE person.id=personId;
IF t_error = 1 THEN
ROLLBACK;
ELSE
COMMIT;
END IF;
select t_error;
END
其中在存储过程中自定义变量使用declare(局部)或者set(全局);
变量查询赋值使用“select 字段 into 变量”的语句;
开启事务start transaction或者begin,需要回滚则需要一个变量判断是否错误,使用DECLARE t_error INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET t_error=1;然后判断t_error的值来判断是否提交还是回滚;
最后调用存储过程使用CALL()方法即可。
网友评论