mysql 自定义函数的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_34789167/article/details/83615253

查看函数功能是否开启:show variables like '%func%'//mysql8 默认为关闭
打开函数功能:SET GLOBAL log_bin_trust_function_creators=1;
关闭函数功能:SET GLOBAL log_bin_trust_function_creators=1;

函数的创建:
语法:

create function 函数名([参数列表]) returns 数据类型
begin
 sql语句;
 return 值;
end;

示例1:

create table class (
id int not null,
cname varchar(10) not null,
primary key(id)
);
-- 最简单的仅有一条sql的函数

create function myselect2() returns int return 666;
select myselect2(); -- 调用函数

--
DELIMITER //  
create function myselect3() returns int
begin 
    declare c int;
    select id from class where cname="python" into c;
    return c;
end;
END//  
DELIMITER ;  
select myselect3();
-- 带传参的函数
create function myselect5(name varchar(15)) returns int
begin 
    declare c int;
    select id from class where cname=name into c;
    return c;
end;
select myselect5("python");

函数的调用:

-- 无参调用
select myselect3();
-- 传参调用
select myselect5("python");
select * from class where id=myselect5("python");

函数的查看:

查看函数创建语句show create function 函数名;
查看所有函数:show function status [like 'pattern'];

函数的删除:drop function 函数名;

实际案例:https://www.cnblogs.com/mafeng/p/7121473.html

创建示例数据库和数据表并插入数据

create database hr;  
use hr;  
  
create table employees  
(  
    employee_id int(11) primary key not null auto_increment,  
    employee_name varchar(50) not null,  
    employee_sex varchar(10) default '男',  
    hire_date datetime not null default current_timestamp,  
    employee_mgr int(11),  
    employee_salary float default 3000,  
    department_id int(11)  
);  
  
  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('David Tian','男',10,7500,1);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Black Xie','男',10,6600,1);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Moses Wang','男',10,4300,1);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Rena Ruan','女',10,5300,1);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Sunshine Ma','女',10,6500,2);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Scott Gao','男',10,9500,2);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Warren Si','男',10,7800,2);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Kaishen Yang','男',10,9500,3);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Simon Song','男',10,5500,3);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Brown Guan','男',10,5000,3);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Eleven Chen','女',10,3500,2);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Cherry Zhou','女',10,5500,4);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Klause He','男',10,4500,5);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Maven Ma','男',10,4500,6);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Stephani Wang','女',10,5500,7);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Jerry Guo','男',10,8500,1);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Gerardo Garza','男',10,25000,8);  
insert into employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) values ('Derek Wu','男',10,5500,5);  
  
  
select * from employees;  

创建函数-根据ID获取员工姓名与员工工资

DELIMITER //  
CREATE FUNCTION GetEmployeeInformationByID(id INT)  
RETURNS VARCHAR(300)  
BEGIN  
    RETURN(SELECT CONCAT('employee name:',employee_name,'---','salary: ',employee_salary) FROM employees WHERE employee_id=id);  
END//  
DELIMITER ;  

使用方法:

扫描二维码关注公众号,回复: 4170980 查看本文章
mysql> select GetEmployeeInformationByID(2);
+----------------------------------------+
| GetEmployeeInformationByID(2)          |
+----------------------------------------+
| employee name:Black Xie---salary: 6600 |
+----------------------------------------+
1 row in set (0.00 sec)

shell> vi function.sql;
DROP FUNCTION IF EXISTS get_sal_level;
DELIMITER $$
CREATE FUNCTION get_sal_level(emp int) RETURNS
VARCHAR(10)
DETERMINISTIC
BEGIN
DECLARE sal_level varchar(10);
DECLARE avg_sal FLOAT;
SELECT AVG(salary) INTO avg_sal FROM salaries WHERE
emp_no=emp;
IF avg_sal < 50000 THEN
SET sal_level = 'BRONZE';
ELSEIF (avg_sal >= 50000 AND avg_sal < 70000) THEN
SET sal_level = 'SILVER';
ELSEIF (avg_sal >= 70000 AND avg_sal < 90000) THEN
SET sal_level = 'GOLD';
ELSEIF (avg_sal >= 90000) THEN
SET sal_level = 'PLATINUM';
ELSE
SET sal_level = 'NOT FOUND';
END IF;
RETURN (sal_level);
END
$$
DELIMITER ;

To create the function:

mysql> SOURCE function.sql;
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
You have to pass the employee number and the function
returns the income level.
mysql> SELECT get_sal_level(10002);
+----------------------+
| get_sal_level(10002) |
+----------------------+
| SILVER |
+----------------------+
1 row in set (0.00 sec)
mysql> SELECT get_sal_level(10001);
+----------------------+
| get_sal_level(10001) |
+----------------------+
| GOLD |
+----------------------+
1 row in set (0.00 sec)
mysql> SELECT get_sal_level(1);
+------------------+
| get_sal_level(1) |
+------------------+
| NOT FOUND |
+------------------+
1 row in set (0.00 sec)

Inbuilt functions 内建函数

MySQL provides numerous inbuilt functions. You have already used the CURDATE() function to get the current date.

mysql> SELECT * FROM employees WHERE hire_date =CURDATE();
mysql> SELECT DATE_ADD(CURDATE(), INTERVAL -7DAY) AS '7 Days Ago';
SELECT CONCAT(first_name, ' ', last_name) FROM employees LIMIT 1;

函数和内建函数:https://dev.mysql.com/doc/refman/8.0/en/func-op-summary-ref.html

Triggers 触发器:使用很少(略)

参考:https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html

Views 视图

View is a virtual table based on the result-set of an SQL statement. It will also have rows and columns just like a real table, but few restrictions, which will be discussed later. Views hide the SQL complexity and, more importantly, provide additional security.

CREATE ALGORITHM=UNDEFINED
DEFINER=`root`@`localhost`
SQL SECURITY DEFINER VIEW salary_view
AS
SELECT emp_no, salary FROM salaries WHERE from_date >
'2002-01-01';
create view view_name
as 
select * from tablename;
[ WITH CHECK OPTION] //保证更新视图是在该视图的权限范围之内。

Now the salary_view view is created and you can query it just like any other table:

mysql> SELECT emp_no, AVG(salary) as avg FROM
salary_view GROUP BY emp_no ORDER BY avg DESC LIMIT
5;

To list all views:SHOW FULL TABLES WHERE TABLE_TYPE LIKE 'VIEW';

参考:https://www.cnblogs.com/geaozhang/p/6792369.html //深入理解mysql视图

EVENTS:事件
查看事件调度是否打开:show variables like '%event_scheduler%';

启动事件调度:SET GLOBAL event_scheduler = ON;

具体参考:https://www.cnblogs.com/qlqwjy/p/7954175.html

PROCESSLIST:
One of the most used views is the process list. It lists all the queries running on the server:

select * from information_schema.processlist;
show processlist;

具体参考:https://www.cnblogs.com/shengdimaya/p/6920677.html //十分钟了结MySQL information_schema

猜你喜欢

转载自blog.csdn.net/sinat_34789167/article/details/83615253
今日推荐