查看是否开启了创建函数的功能
SHOW VARIABLES LIKE '%fun%';
如果为off需要开启
SET GLOBAL log_bin_trust_function_creators=1;
创建函数
-- RETURNS
CREATE FUNCTION fun_add(a INT,b INT)
RETURNS INT
BEGIN
RETURN a+b;
END;
$;
调用函数
SELECT fun_add(3,4);
查看函数
show create function fun_add;
删除函数
DROP FUNCTION fun_add;
CREATE TABLE userinfo(
username VARCHAR(20) NOT NULL DEFAULT '123',
userpwd VARCHAR(20) NOT NULL DEFAULT '123'
);
INSERT INTO userinfo VALUES('wxj','wxj123');
INSERT INTO userinfo VALUES('wxj1','wxj123');
INSERT INTO userinfo VALUES('wxj12','wxj123');
INSERT INTO userinfo VALUES('wxj123','wxj123');
创建登录查询函数
CREATE FUNCTION fun_log(name VARCHAR(20),pwd VARCHAR(20))
RETURNS VARCHAR(20)
BEGIN
DECLARE result INT DEFAULT 0;
SELECT COUNT(*) INTO result FROM userinfo WHERE username=name;
IF result=0 THEN
RETURN 'username error';
END IF;
SELECT COUNT(*) INTO result FROM userinfo WHERE username=name && userpwd=pwd;
IF result = 0 THEN
RETURN 'password error';
ELSE
RETURN' log success';
END IF;
END;
$;
mysql> select fun_log('w22xj','wxj123');
+---------------------------+
| fun_log('w22xj','wxj123') |
+---------------------------+
| username error |
+---------------------------+
1 row in set (0.00 sec)
mysql> select fun_log('wxj','wxj1213');
+--------------------------+
| fun_log('wxj','wxj1213') |
+--------------------------+
| password error |
+--------------------------+
1 row in set (0.00 sec)
mysql> select fun_log('wxj','wxj123');
+-------------------------+
| fun_log('wxj','wxj123') |
+-------------------------+
| log success |
+-------------------------+
1 row in set (0.00 sec)
MySQL_函数的创建以及使用
最新推荐文章于 2024-08-21 15:00:00 发布