1,Mysql手册中把function和procedure放在一起讲解,这个是造成大家困扰的很大一个方面。其实,function就当作 php的function来理解就ok,而procedure是实现某一个功能的一整套动作和过程。function很简单,执行了他,得到对应想要的结果,如:截取字符串;而procedure用来实现某一个用例,如做一连串的数据库操作。
2,procedure有in\out\inout类型的参数,但function只有默认的in类型的参数。至于procedure中in等类型怎样用,请参考:http://blog.csdn.net/ethansky/archive/2009/08/20/4467178.aspx 这位仁兄写的超级详细。
3,function 总是要有明确的return来返回结果,而procedure需要另外的方式来做。
4,一些实践:
a,一个自定义的function:
DELIMITER $$
DROP FUNCTION IF EXISTS `hello`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `hello`(s CHAR(20)) RETURNS char(50) CHARSET utf8
RETURN CONCAT(’Hello, ‘,s,’!')$$
DELIMITER ;
我可以这样将自定义函数直接用于SQL中:
insert into test (name,status) values (hello(’a'),1);
b,对于procedure,可以这样:
DELIMITER $$
DROP PROCEDURE IF EXISTS `add_comment`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `add_comment`(`entry_id` int,`new_content` text)
BEGIN
DECLARE true_id int DEFAULT 0;
select `id` into true_id from `sgtest`.`blog_entries` where `id`=entry_id;
IF true_id>0 THEN
insert into `sgtest`.`blog_comments` (`entry_id`,`content`) values(entry_id,hello(new_content) );
END IF;
END$$
转载:http://www.bumao.com/index.php/2010/05/mysql-function-vs-procedure.html
2,procedure有in\out\inout类型的参数,但function只有默认的in类型的参数。至于procedure中in等类型怎样用,请参考:http://blog.csdn.net/ethansky/archive/2009/08/20/4467178.aspx 这位仁兄写的超级详细。
3,function 总是要有明确的return来返回结果,而procedure需要另外的方式来做。
4,一些实践:
a,一个自定义的function:
DELIMITER $$
DROP FUNCTION IF EXISTS `hello`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `hello`(s CHAR(20)) RETURNS char(50) CHARSET utf8
RETURN CONCAT(’Hello, ‘,s,’!')$$
DELIMITER ;
我可以这样将自定义函数直接用于SQL中:
insert into test (name,status) values (hello(’a'),1);
b,对于procedure,可以这样:
DELIMITER $$
DROP PROCEDURE IF EXISTS `add_comment`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `add_comment`(`entry_id` int,`new_content` text)
BEGIN
DECLARE true_id int DEFAULT 0;
select `id` into true_id from `sgtest`.`blog_entries` where `id`=entry_id;
IF true_id>0 THEN
insert into `sgtest`.`blog_comments` (`entry_id`,`content`) values(entry_id,hello(new_content) );
END IF;
END$$
转载:http://www.bumao.com/index.php/2010/05/mysql-function-vs-procedure.html