一 创建语法
create function 函数名(参数列表) returns 返回类型
DETERMINISTIC
begin
函数体
End
二 调用语法
select 函数名(参数列表)
三 删除和查看
查看:
show create function 函数名
删除:
drop function 函数名
四 示例(比较两字符串的差异,并返回)
4.1 创建测试表
DROP TABLE IF EXISTS `teststr`;
CREATE TABLE `teststr` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '唯一标识',
`str1` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '字符串1',
`str2` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '字符串2',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
INSERT INTO `teststr` VALUES (1, '123', '12');
INSERT INTO `teststr` VALUES (2, 'ab', 'ac');
INSERT INTO `teststr` VALUES (3, 'ab', 'cd');
4.2 创建自定义函数
create function find_str_dif(a VARCHAR(255),b VARCHAR(255), dir varchar(255))
returns varchar(255) CHARSET utf8mb4
DETERMINISTIC
begin
declare c int default 1; #定义计数变量
declare str VARCHAR(255) DEFAULT ''; #定义返回结果
#只返回左边
if(dir='left') then
while(LENGTH(a)>=c)do
if(locate(substring(a,c,1),b)=0) then
set str=concat(str,substring(a,c,1));
end if;
set c=c+1;
end while;
set c=1;
end if;
#只返回右边
if(dir='right') then
while(LENGTH(b)>=c)do
if(locate(substring(b,c,1),a)=0) then
set str=concat(str,substring(b,c,1));
end if;
set c=c+1;
end while;
set c=1;
end if;
#返回全部差异
if(dir='all') then
while(LENGTH(a)>=c)do
if(locate(substring(a,c,1),b)=0) then
set str=concat(str,substring(a,c,1));
end if;
set c=c+1;
end while;
set c=1;
while(LENGTH(b)>=c)do
if(locate(substring(b,c,1),a)=0) then
set str=concat(str,substring(b,c,1));
end if;
set c=c+1;
end while;
set c=1;
end if;
return str;
end
4.3 测试结果展示
4.4 创建函数所用到的MySQL函数说明
-- locate(substr,str)函数,判断字符串是否被包含,包含返回1,不包含返回0
select locate('a','abc') -- 1
-- substring(str,index,num) 返回字符串从第index位开始的num个字符
select SUBSTRING('abcd',3,1) --c
-- length(str)函数,返回字符串长度
select length('abc') --3