-- 創建班級信息表:
create table xidian_class (
id int primary key auto_increment,
class varchar(10),
room int
);
-- 插入數據
insert into xidian_class values
(NULL,'xd0115',207),
(NULL,'xd0228',104),
(NULL,'xd0331',102),
(NULL,'xd0505',202);
-- 創建學生信息表
create table xidian_stu (
stu_id int primary key auto_increment,
stu_no varchar(10),
class_id int,
stu_name varchar(10)
);
-- 插入一條數據
insert into xidian_stu values(NULL,'xd0115004',3,'李娜');
-- 自動生成學號函數
delimiter $$
create function xd_sno(c_id int) returns char(10)
begin
declare s_no char(10); #保存當前班級內最大學號,如果沒有就是NULL
declare class_name char(6);
-- 找最大學號
select stu_no from xidian_stu where class_id = c_id order by stu_no desc into s_no ;
if isnull(s_no ) then
-- 沒有學生從1開始獲得班級學號
select class from xidian_class where c_id = id into class_name;
return concat(class_name, '001');
else
-- 有學生,則最大學號加1
return concat(left(s_no, 6) , lpad(right(s_no, 3) + 1, 3, '0'));
end if;
end
$$
delimiter ;
結果: