mysql 创建函数

<pre name="code" class="html">root 用户创建函数;

delimiter $$ 
CREATE  FUNCTION `loadTreeByParent`(begin_sn INT) RETURNS varchar(600) CHARSET utf8
BEGIN 
	DECLARE rest VARCHAR(600);
	DECLARE temp VARCHAR(60);
	SET rest='$';
	SET temp=CAST(begin_sn AS CHAR);
	
	WHILE temp IS NOT NULL DO
		SET rest=CONCAT(rest,',',temp);
		SELECT GROUP_CONCAT(sn) INTO temp FROM ClientManager WHERE FIND_IN_SET(parent,temp)>0;
	END WHILE;
	RETURN rest;
END$$


CREATE DEFINER=`root`@`%` FUNCTION `loadTreeByParent`(begin_sn INT) RETURNS varchar(600) CHARSET utf8
BEGIN 
	DECLARE rest VARCHAR(600);
	DECLARE temp VARCHAR(60);
	SET rest='$';
	SET temp=CAST(begin_sn AS CHAR);
	
	WHILE temp IS NOT NULL DO
		SET rest=CONCAT(rest,',',temp);
		SELECT GROUP_CONCAT(sn) INTO temp FROM ClientManager WHERE FIND_IN_SET(parent,temp)>0;
	END WHILE;
	RETURN rest;
END


zjzc_app 创建函数;

drop function loadTreeByParent;

CREATE DEFINER=`zjzc_app`@`%` FUNCTION `loadTreeByParent`(begin_sn INT) RETURNS varchar(600) CHARSET utf8
BEGIN 
	DECLARE rest VARCHAR(600);
	DECLARE temp VARCHAR(60);
	SET rest='$';
	SET temp=CAST(begin_sn AS CHAR);
	
	WHILE temp IS NOT NULL DO
		SET rest=CONCAT(rest,',',temp);
		SELECT GROUP_CONCAT(sn) INTO temp FROM ClientManager WHERE FIND_IN_SET(parent,temp)>0;
	END WHILE;
	RETURN rest;
END


用root用户登录,执行;
zjzc-mysql:/root# cat t1.sql 
	$$ 
CREATE DEFINER=`zjzc_app`@`%` FUNCTION `loadTreeByParent`(begin_sn INT) RETURNS varchar(600) CHARSET utf8
BEGIN 
	DECLARE rest VARCHAR(600);
	DECLARE temp VARCHAR(60);
	SET rest='$';
	SET temp=CAST(begin_sn AS CHAR);	
	WHILE temp IS NOT NULL DO
		SET rest=CONCAT(rest,',',temp);
		SELECT GROUP_CONCAT(sn) INTO temp FROM ClientManager WHERE FIND_IN_SET(parent,temp)>0;
	END WHILE;
	RETURN rest;
END$$
zjzc-mysql:/root# mysql -A -uroot -p1234567
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 241
Server version: 5.6.22-log Source distribution

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

mysql> use zjzc;
Database changed
mysql> source t1.sql
ERROR 1304 (42000): FUNCTION loadTreeByParent already exists

mysql> drop function loadTreeByParent
    -> ;
Query OK, 0 rows affected (0.00 sec)

mysql> source t1.sql
Query OK, 0 rows affected (0.00 sec)


[DEFINER = { user | CURRENT_USER }]:定义创建者,可以手动指定数据库中已经存在的用户,或者默认(使用当前用户).



                                    
原文地址:https://www.cnblogs.com/hzcya1995/p/13350727.html