我已经创建了一个存储过程来删除多个表中的数据。我的工作流程如下
我使用的是MySQL5.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‘
我不知道为什么它不给另外两个sps打电话。我是mysql存储过程的newbee。有人能帮帮我吗?
提前感谢
sameera
发布于 2011-01-07 03:39:59
我不知道你为什么要使用游标--你所需要的就是下面这样的东西:
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);
*/https://stackoverflow.com/questions/4618781
复制相似问题