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);
复制代码
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 逛动物园();
复制代码