我创建了一个存储过程来从多个表中删除数据。我的工作流程如下
我正在使用 mysql 5.0 并在 Linux 上运行
表依赖关系如下
表 C 取决于表 B 表 B 取决于表 A
我想删除A表中的一条记录,并删除B表和C表中的所有相关记录
1 - 删除明细表 (C) 中的所有数据(使用存储过程 sp_delete_from_C)
2 - 删除相关数据直接子表(B)(使用存储过程sp_delete_from_B)
3 - 删除主表 (A)(使用存储过程 sp_delete_from_A)
我写了以下程序
CREATE PROCEDURE sp_A_rollback(IN aId INT UNSIGNED)
READS SQL DATA
BEGIN
DECLARE b_id INT DEFAULT 0;
DECLARE cur_1 CURSOR FOR SELECT id FROM b where a_id=aId;
OPEN cur_1;
read_loop: LOOP
FETCH cur_1 INTO a_id;
CALL sp_delete_from_C(b_id);
END LOOP;
CLOSE cur_1;
CALL sp_delete_from_B(aId);
CALL sp_delete_from_A(aId);
END //
我的问题是,
如果我单独运行这些程序,它就会起作用
但是如果你运行 sp_A_rollback 它只执行 'sp_delete_from_C'
我不知道为什么它不调用其他 2 个 sps。我是 mysql 存储过程的新手。请有人帮助我
提前致谢
同一个
最佳答案
我不知道你为什么使用游标 - 你所需要的只是如下所示:
drop procedure if exists cascade_delete_tableA;
delimiter #
create procedure cascade_delete_tableA
(
in p_id int unsigned
)
begin
delete from tableC where a_id = p_id;
delete from tableB where a_id = p_id;
delete from tableA where id = p_id;
end#
delimiter ;
从包含在事务中的应用程序代码中调用存储过程。
编辑
您需要使用联接来从 tableC 中删除行。这里有一个比较全面的例子供大家学习http://pastie.org/1435521 。此外,您的游标循环没有获取正确的变量,这就是它无法以当前形式工作的原因。我仍然建议您检查以下内容...
-- TABLES
drop table if exists customers;
create table customers
(
cust_id smallint unsigned not null auto_increment primary key,
name varchar(255) not null
)
engine=innodb;
drop table if exists orders;
create table orders
(
order_id int unsigned not null auto_increment primary key,
cust_id smallint unsigned not null
)
engine=innodb;
drop table if exists order_items;
create table order_items
(
order_id int unsigned not null,
prod_id smallint unsigned not null,
primary key (order_id, prod_id)
)
engine=innodb;
-- STORED PROCS
drop procedure if exists cascade_delete_customer;
delimiter #
create procedure cascade_delete_customer
(
in p_cust_id smallint unsigned
)
begin
declare rows int unsigned default 0;
-- delete order items
delete oi from order_items oi
inner join orders o on o.order_id = oi.order_id and o.cust_id = p_cust_id;
set rows = row_count();
-- delete orders
delete from orders where cust_id = p_cust_id;
set rows = rows + row_count();
-- delete customer
delete from customers where cust_id = p_cust_id;
select rows + row_count() as rows;
end#
delimiter ;
-- TEST DATA
insert into customers (name) values ('c1'),('c2'),('c3'),('c4');
insert into orders (cust_id) values (1),(2),(3),(1),(1),(3),(2),(4);
insert into order_items (order_id, prod_id) values
(1,1),(1,2),(1,3),
(2,5),
(3,2),(3,5),(3,8),
(4,1),(4,4),
(5,2),(5,7),
(6,4),(6,8),(6,9),
(7,5),
(8,3),(8,4),(8,5),(8,6);
-- TESTING
/*
select * from customers where cust_id = 1;
select * from orders where cust_id = 1;
select * from order_items oi
inner join orders o on oi.order_id = o.order_id and o.cust_id = 1;
call cascade_delete_customer(1);
*/
关于mysql - 存储过程+mysql问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4618781/