Mysql8.0习题系列
软件下载地址 提取码:7v7u 数据下载地址 提取码:e6p9
mysql创建函数基本语法如下:
delimiter $
create function 函数名(参数) returns 返回类型
begin
return 函数体;
end $
函数调用如下:
select 函数名()
准备工作
USE test15_pro_func;
CREATE TABLE employees
AS
SELECT * FROM atguigudb.`employees`;
CREATE TABLE departments
AS
SELECT * FROM atguigudb.`departments`;
#注意在mysql8.0中,创建函数如果不加入函数特征,则首先要定义全局变量如下
SET GLOBAL log_bin_trust_function_creators = 1;
1. 创建函数get_count(),返回公司的员工个数
DELIMITER $;
CREATE FUNCTION get_count() RETURNS INT
BEGIN
RETURN (SELECT COUNT(*) FROM employees);
END $;
DELIMITER ;
SELECT get_count();
#有参有返回
2. 创建函数ename_salary(),根据员工姓名,返回它的工资
DELIMITER $;
CREATE FUNCTION ename_salary(ename VARCHAR(20)) RETURNS DOUBLE
BEGIN
RETURN (SELECT salary FROM employees WHERE last_name = ename);
END $;
DELIMITER ;
SELECT ename_salary('Abel');
3. 创建函数dept_sal() ,根据部门名,返回该部门的平均工资
DELIMITER $;
CREATE FUNCTION dept_sal(deptname VARCHAR(20)) RETURNS DOUBLE
BEGIN
RETURN (SELECT AVG(salary)
FROM employees e JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_name = deptname
);
END $;
DELIMITER ;
SELECT dept_sal(‘Marketing’);
4. 创建函数add_float(),实现传入两个float,返回二者之和
DELIMITER $;
CREATE FUNCTION add_float(num1 FLOAT, num2 FLOAT) RETURNS FLOAT
BEGIN
RETURN(num1+num2);
END $;
DELIMITER ;
SELECT add_float(0.3,0.6);
|