我会连续用一两个表,陆续出一些题目,同时也会给出答案,题目一般含有视图触发器,函数,存储过程
自定义函数例题:
还是那个富豪榜,有id、姓名、年龄、身价
当你需要插入一个富豪信息时
往函数中传参,传入他的个人信息,之后
你需要知道和他身价相等的富豪总数是多少人
语法:
create function 函数名([参数列表]) returns 数据类型
begin
sql语句; #也可以写逻辑语句
return 值;
end;
如果不了解语法的含义,看我的另一篇文章:
触发器语法讲解
答案:
尽量自己做下^_^
创建富豪表
create table wealthy(
id int primary key auto_increment,
age int,
name varchar(20),
money int);
插入需要的数据
insert into wealthy values(1,20,'张三',110);
insert into wealthy values(2,35,'李四',110);
insert into wealthy values(3,35,'王五',90);
insert into wealthy values(4,20,'赵六',90);
创建平民表
create table person(
id int primary key auto_increment,
age int,
name varchar(20),
money int);
插入需要的数据
insert into person values(0,20,'十一',30);
创建函数,变量的定义要放在前面
delimiter $$
create function num(names varchar(20),ages int,moneys int) returns int
begin
declare n int default 0;
insert into wealthy values(0,ages,names,moneys);
select count(*) into n from wealthy where money=moneys;
set n= n-1;
return n;
end;
$$
delimiter ;
调用函数
select num('十二',29,110);
查看函数
show create function num \G;
show function status like 'num'\G; #在所有函数中模糊查询
删除函数
drop function num;