MySQL自定义函数

语法

CREATE
    [DEFINER = user]
    FUNCTION sp_name ([func_parameter[,...]])
    RETURNS type
    [characteristic ...] routine_body

func_parameter:
    param_name type

characteristic:
    COMMENT 'string'
  | LANGUAGE SQL
  | [NOT] DETERMINISTIC
  | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
  | SQL SECURITY { DEFINER | INVOKER }

实例

创建函数

DELIMITER $$

USE `world`$$

DROP FUNCTION IF EXISTS `func1`$$

CREATE DEFINER=`root`@`10.0.0.%` FUNCTION `func1`() RETURNS INT(11)
    -- DETERMINISTIC
BEGIN
    DECLARE res VARCHAR(20);
    
    SELECT COUNT(*) INTO res FROM t4;
    
    RETURN res;
    END$$

DELIMITER ;

这时候会报错1418

错误代码: 1418
This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)

意思是说,函数每次调用的时候会出现不同的结果。这时需要使用

DETERMINISTIC 或者 NOT DETERMINISTIC 指明是否产生明确的结果
DELIMITER $$

USE `world`$$

DROP FUNCTION IF EXISTS `func1`$$

CREATE DEFINER=`root`@`10.0.0.%` FUNCTION `func1`() RETURNS INT(11)
   DETERMINISTIC
BEGIN
    DECLARE res VARCHAR(20);
    
    SELECT COUNT(*) INTO res FROM t4;
    
    RETURN res;
    END$$

DELIMITER ;

调用

SELECT func1()

查看、删除函数

mysql> select * from information_schema.routines\G
mysql> delete function func_name;

早期版本查看函数

  select `name` from mysql.proc where db = 'xx' and `type` = 'FUNCTION'   //函数

查看函数状态

show function status;     //函数

 










你可能感兴趣的:(MySQL自定义函数)