我不知道爲什麼你使用遊標 - 所有你需要的是類似以下內容:
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 ;
通話存儲過程從應用程序代碼中包裝在一個事務中。
編輯
你需要使用連接到您的表C刪除行。這是一個更全面的例子,供你學習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);
*/
嗨f00,感謝您的答案。我在這裏使用遊標,因爲從表C中刪除我只有表B的關鍵。因爲我需要一個循環,我使用遊標。在真正的renario我不得不使用其他存儲過程,而不是直接刪除語句(因爲涉及到一些邏輯和這些過程已經實施)。所以我必須調用這個SP內的其他sps。任何想法,再次感謝您的答案 – sameera207 2011-01-06 19:55:30