Home > Database > Mysql Tutorial > 深入mysql创建自定义函数与存储过程的详解_MySQL

深入mysql创建自定义函数与存储过程的详解_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 13:24:34
Original
990 people have browsed it

bitsCN.com

一 创建自定义函数
在使用mysql的过程中,mysql自带的函数可能不能完成我们的业务需求,这时就需要自定义函数,例如笔者在开发过程中遇到下面这个问题:
mysql表结构如下

DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pic` varchar(50) NOT NULL,
  `hashcode` varchar(16) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of test
-- ----------------------------
INSERT INTO `test` VALUES ('1', '2012120910403250c3fa209bf48.jpg', 'bf8f83818080c0f1');
INSERT INTO `test` VALUES ('2', '2012120620430750c092db26557.JPG', 'ff9880f0f680ceff');
INSERT INTO `test` VALUES ('3', '2012120619582550c08861eb062.jpg', '7f7f004f7f7f7c7f');
INSERT INTO `test` VALUES ('4', '2012112911072650b6d16e7f21f.jpg', '7f7f004f7f7f007f');

其中pic字段为图片名称,hashcode是图片的感知哈希编码(16进制编码字符串,长度固定16位),用户输入一个hashcode,怎么从数据库中找出满足字符串对应位置的字符不同的个数小于5的记录呢?就像“11001”和“11101”对应位置不同字符不同的个数为1,比如 用户输入"7f7f004f7f7f00af",那么第三条和第四条记录是满足的,怎么实现呢?如果单纯的依靠mysql自带的函数很难完成,这时就需要建立自定义函数解决。这个问题的解决在此非常感谢csdn的acmain_chm,acmain_chm以及oschina的@梁小刚,还有@淘宝丁奇

建立自定义函数的过程如下:
1.进入mysql命令行
mysql>
2.用delimiter命令来把语句定界符从 ;变为//。这样就允许在程序体用;定界符传递到服务器,而不是被mysql自己来解释。
mysql> delimiter //
3.创建自定义函数

mysql>CREATE FUNCTION hashDiff( s1 varchar(16), s2 varchar(16))
->RETURNS INT
->BEGIN
->DECLARE diff, x INT;
->SET diff =0;
->SET x = 0;
->WHILE (x  ->SET x = x+1;
->if SUBSTRING(s1, x,1)SUBSTRING(s2, x,1) then
->set diff=diff+ 1;
->end if;
->END WHILE;
->RETURN diff;
->END
->//
mysql>select * from test t where  hashDiff(t.hashcode,'ff9880f0f680ceff') 
二 创建存储过程
1.进入mysql命令行
mysql>
2.用delimiter命令来把语句定界符从 ;变为//。这样就允许在程序体用;定界符传递到服务器,而不是被mysql自己来解释。
mysql> delimiter //
3.创建存储过程

mysql> delimiter //
mysql> CREATE PROCEDURE simpleproc (OUT param1 INT)
    -> BEGIN
    ->   SELECT COUNT(*) INTO param1 FROM t;
    -> END
    -> //
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> CALL simpleproc(@a);
Query OK, 0 rows affected (0.00 sec)


mysql> SELECT @a;
+------+
| @a   |
+------+
| 3    |
+------+
1 row in set (0.00 sec)

bitsCN.com
Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
MySQL stops process
From 1970-01-01 08:00:00
0
0
0
Error when installing mysql on linux
From 1970-01-01 08:00:00
0
0
0
phpstudy cannot start mysql?
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template