03_存储过程案例练习
create table books(
book_id int primary key auto_increment,
book_name varchar(50) not null,
book_author varchar(20) not null,
book_price decimal(10,2) not null,
book_stock int not null,
book_desc varchar(200)
);
insert into books(book_name,book_author,book_price,book_stock,book_desc)
values('Java程序设计','亮亮',38.80,12,'亮亮老师带你学Java');
insert into books(book_name,book_author,book_price,book_stock,book_desc)
values('Java王者之路','威哥',44.40,9,'千锋威哥,Java王者领路人');
create table students(
stu_num char(4) primary key,
stu_name varchar(20) not null,
stu_gender char(2) not null,
stu_age int not null
);
insert into students(stu_num,stu_name,stu_gender,stu_age) values('1001','张三','男',20);
insert into students(stu_num,stu_name,stu_gender,stu_age) values('1002','李四','女',20);
insert into students(stu_num,stu_name,stu_gender,stu_age) values('1003','王五','男',20);
create table records(
rid int primary key auto_increment,
snum char(4) not null,
bid int not null,
borrow_num int not null,
is_return int not null,
borrow_date date not null,
constraint FK_RECORDS_STUDENTS foreign key(snum) references students(stu_num),
constraint FK_RECORDS_BOOKS foreign key(bid) REFERENCES books(book_id)
);
create procedure proc_borrow_book(IN a char(4),IN b int, IN m int,OUT state int)
begin
declare stu_count int default 0;
declare book_count int default 0;
declare stock int default 0;
select count(stu_num) INTO stu_count from students where stu_num=a;
if stu_count>0 then
select count(book_id) INTO book_count from books where book_id=b;
if book_count >0 then
select book_stock INTO stock from books where book_id=b;
if stock >= m then
insert into records(snum,bid,borrow_num,is_return,borrow_date) values(a,b,m,0,sysdate());
update books set book_stock=stock-m where book_id=b;
set state=1;
else
set state=4;
end if;
else
set state = 3;
end if;
else
set state = 2;
end if;
end;
set @state=0;
call proc_borrow_book('1001',1,2,@state);
select @state from dual;