MySQLl 2019-04-06
一 创建自定义函数
在使用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');
建立自定义函数的过程如下:
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 < 16 ) DO ->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') < 5;
代码如下:
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)