[MySQL光速入门]025 函数做业答案

  1. 建立一个累加的函数, 两个参数, 从第一个参数累加到第二个参数
mysql> select accumulation(1,100);
+---------------------+
| accumulation(1,100) |
+---------------------+
|                5050 |
+---------------------+
1 row in set (0.02 sec)

mysql> 
复制代码

答案:mysql

drop function if exists accumulation;
create function accumulation(start_num int, end_num int) returns int begin 
    declare result int default 0;
    while 
        start_num <= end_num
    do
        set result = result + start_num;
        set start_num = start_num + 1;
    end while;
    return result;
end;
select accumulation(1,100);
复制代码

中文版sql

drop function if exists 累加;
create function 累加(开始数字 int, 结束数字 int) returns int begin 
    declare 最终结果 int default 0;
    while 
        开始数字 <= 结束数字
    do
        set 最终结果 = 最终结果 + 开始数字;
        set 开始数字 = 开始数字 + 1;
    end while;
    return 最终结果;
end;
select 累加(1,100);
复制代码
  1. 建立一个函数叫动物园, 每次调用, 随机返回不一样的动物
mysql> select zoo();
+--------+
| zoo()  |
+--------+
| 眼镜蛇 |
+--------+
1 row in set (0.03 sec)

mysql> select zoo();
+--------+
| zoo()  |
+--------+
| 白头鹰 |
+--------+
1 row in set (0.04 sec)

mysql> select zoo();
+-------+
| zoo() |
+-------+
| 河马  |
+-------+
1 row in set (0.06 sec)

mysql> select zoo();
+-------+
| zoo() |
+-------+
| 隼    |
+-------+
1 row in set (0.07 sec)

mysql> select zoo();
+--------+
| zoo()  |
+--------+
| 白头鹰 |
+--------+
1 row in set (0.09 sec)

mysql> select zoo();
+-------+
| zoo() |
+-------+
| 猩猩  |
+-------+
1 row in set (0.10 sec)

mysql> select zoo();
+-------+
| zoo() |
+-------+
| 鬣狗  |
+-------+
1 row in set (0.11 sec)

mysql> 
复制代码

答案:函数

drop function if exists zoo;
create function zoo() returns char(20) begin 
    declare result char(20);
    declare animals_id int;
    set animals_id = floor(rand()*20) + 1;
    select name into result from animals where id = animals_id;
    return result;
end;
select zoo();
复制代码

中文版post

drop function if exists 逛动物园;
create function 逛动物园() returns char(20) begin 
    declare 结果 char(20);
    declare 动物ID int;
    set 动物ID = floor(rand()*20) + 1;
    select 动物名称 into 结果 from 动物表 where id = 动物ID;
    return 结果;
end;
select 逛动物园();
复制代码

快速跳转

相关文章
相关标签/搜索