1、先查看函数功能是否开启:show variables like '%func%';
若是未开启则:SET GLOBAL log_bin_trust_function_creators=1;
关闭则是:SET GLOBAL log_bin_trust_function_creators=0;
2、自定义函数:
delimiter $$;
这个函数是合并两个字符串
delimiter $$;
DROP FUNCTION IF EXISTS addMaterialName $$;
CREATE FUNCTION addMaterialName(materialName VARCHAR(255),cheName VARCHAR(255))
RETURNS VARCHAR(255)
BEGIN
DECLARE newName VARCHAR(255) DEFAULT '';
IF(ISNULL(materialName) or materialName ='') THEN set newName = cheName;
ELSEIF (ISNULL(cheName) or TRIM(cheName) ='')
THEN set newName = materialName;
ELSE set newName = CONCAT(materialName,'(',cheName,')');
END IF;
RETURN newName;
END $$;
delimiter ;
3、查看函数:
show function status;
其它自定义函数:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Function structure for caseChoose
-- ----------------------------
DROP FUNCTION IF EXISTS `caseChoose`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `caseChoose`(`chooseNum` int) RETURNS int(11)
BEGIN
-- case 选择欲绝
case chooseNum
when 1 THEN RETURN 100;
when 2 THEN RETURN 200;
else RETURN 300;
end case;
END
;;
DELIMITER ;
-- ----------------------------
-- Function structure for forNum
-- ----------------------------
DROP FUNCTION IF EXISTS `forNum`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `forNum`(`chooseNum` int) RETURNS int(11)
BEGIN
-- loop1 :标志位:开始循环
loop1: LOOP
SET chooseNum=chooseNum+1;
IF chooseNum=100
-- 跳出本次循环
then ITERATE loop1;
elseif chooseNum = 200
-- 跳出循环
THEN LEAVE loop1;
-- if要有结束语句否则错误
end if;
-- 结束循环 标志位
end loop loop1;
-- 返回内容
RETURN chooseNum +1;
END
;;
DELIMITER ;
-- ----------------------------
-- Function structure for forNumRepeat
-- ----------------------------
DROP FUNCTION IF EXISTS `forNumRepeat`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `forNumRepeat`(`chooseNum` int) RETURNS int(11)
BEGIN
-- REPEAT语句是有条件控制的循环语句。当满足特定条件时,就会跳出循环语句
-- [begin_label:] REPEAT
-- statement_list
-- UNTIL search_condition
-- END REPEAT [end_label]
REPEAT
SET chooseNum=chooseNum+1;
-- 当数据为100的时候结束语句
UNTIL chooseNum=100
END REPEAT ;
RETURN chooseNum + 2;
END
;;
DELIMITER ;
-- ----------------------------
-- Function structure for forNumWhile
-- ----------------------------
DROP FUNCTION IF EXISTS `forNumWhile`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `forNumWhile`(`chooseNum` int) RETURNS int(11)
BEGIN
-- while do 语句:
WHILE chooseNum<100 DO
SET chooseNum=chooseNum+1000;
END WHILE ;
return chooseNum;
END
;;
DELIMITER ;
-- ----------------------------
-- Function structure for ifNum
-- ----------------------------
DROP FUNCTION IF EXISTS `ifNum`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ifNum`(`id` int,`num` int) RETURNS int(11)
BEGIN
-- if 条件判断语句
if id < 3 THEN RETURN id;
ELSEIF num > 3 then RETURN num;
else RETURN 123;
end if;
END
;;
DELIMITER ;