function
Meaning : A set of pre-compiled SQL statements, understood as a batch statement.
Benefits :
1. Improve code reuse
2. Simplify operations
3. Reduce the number of compilations and reduce the number of connections to the database server, which improves efficiency
The difference between functions and stored procedures:
Stored procedure: There can be 0 returns or multiple returns, suitable for batch insertion and batch update
Function: one and only one return, suitable for processing data and return a result
(1) Create function:
CREATE FUNCTION 函数名([func_parameter[,...]] RETURNS 返回类型
BEGIN
函数体
END
func_parameter: param_name type
Function body: There must be a return statement, otherwise an error will be reported
(2) Call function:
select 函数名(参数列表)
example:
# 案例1:根据员工名,返回它的工资
CREATE FUNCTION myf2(empName VARCHAR(20)) RETURNS DOUBLE
BEGIN
SET @sal=0;#定义用户变量
SELECT salary INTO @sal #赋值
FROM employees
WHERE last_name = empName;
RETURN @sal;
END $
SELECT myf2('Chen') $ # 调用
# 案例2:创建函数,实现传入两个float, 返回二者之和
DELIMITER $$
CREATE FUNCTION test_fun1(num1 FLOAT,num2 FLOAT) RETURNS FLOAT
BEGIN
DECLARE SUM FLOAT DEFAULT 0;
SET SUM=num1+num2;
RETURN SUM;
END $$
SELECT test_fun1(1, 2);
(3) Modify function:
alter function function name [charactristic...]
(4) Delete function:
drop function [if exits] function name
(5) View function:
(1) View the status of the function:
show function status like function name
(2) View the definition of the function:
show create function function name
(3) Learn about function information by viewing information_schema.routines
select * from routines where rounies_name=function name