1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
-- 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);

*/