咱们你们都知道MySQL 存储过程是从 MySQL 5.0 开始逐渐增长新的功能。存储过程在实际应用中也是优势大于缺点。不过最主要的仍是执行效率和SQL 代码封装。特别是 SQL 代码封装功能,若是没有存储过程。mysql
在外部程序访问数据库时(例如 PHP),要组织不少 SQL 语句。sql
特别是业务逻辑复杂的时候,一大堆的 SQL 和条件夹杂在 PHP 代码中,让人毛骨悚然。如今有了 MySQL 存储过程,业务逻辑能够封装存储过程当中,这样不只容易维护,并且执行效率也高。数据库
1、MySQL 建立存储过程函数
“pr_add” 是个简单的 MySQL 存储过程,这个MySQL 存储过程有两个 int 类型的输入参数 “a”、“b”,返回这两个参数的和。spa
drop procedure if exists pr_add;
计算两个数之和code
create procedure pr_add ( a int, b int ) begin declare c int; if a is null then set a = 0; end if; if b is null then set b = 0; end if; set c = a + b; select c as sum; /* return c;
不能在 MySQL 存储过程当中使用。return 只能出如今函数中。class
*/ end;
2、调用 MySQL 存储过程效率
call pr_add(10, 20);
执行 MySQL 存储过程,存储过程参数为 MySQL 用户变量。变量
set @a = 10; set @b = 20; call pr_add(@a, @b);
3、MySQL 存储过程特色select
建立 MySQL 存储过程的简单语法为:
create procedure 存储过程名字() ( [in|out|inout] 参数 datatype ) begin MySQL 语句; end;
MySQL 存储过程参数若是不显式指定“in”、“out”、“inout”,则默认为“in”。习惯上,对因而“in” 的参数,咱们都不会显式指定。
1. MySQL 存储过程名字后面的“()”是必须的,即便没有一个参数,也须要“()”
2. MySQL 存储过程参数,不能在参数名称前加“@”,如:“@a int”。下面的建立存储过程语法在 MySQL 中是错误的(在 SQL Server 中是正确的)。 MySQL 存储过程当中的变量,不须要在变量名字前加“@”,虽然 MySQL 客户端用户变量要加个“@”。
create procedure pr_add ( @a int, -- 错误 b int -- 正确 )
3. MySQL 存储过程的参数不能指定默认值。
4. MySQL 存储过程不须要在 procedure body 前面加 “as”。而 SQL Server 存储过程必须加 “as” 关键字。
create procedure pr_add ( a int, b int ) as -- 错误,MySQL 不须要 “as” begin mysql statement ...; end;
5. 若是 MySQL 存储过程当中包含多条 MySQL 语句,则须要 begin end 关键字。
create procedure pr_add ( a int, b int ) begin mysql statement 1 ...; mysql statement 2 ...; end;
6. MySQL 存储过程当中的每条语句的末尾,都要加上分号 “;”
... declare c int; if a is null then set a = 0; end if; ... end;
7. MySQL 存储过程当中的注释。
/* 这是个 多行 MySQL 注释。 */ declare c int; -- 这是单行 MySQL 注释 (注意 -- 后至少要有一个空格) if a is null then # 这也是个单行 MySQL 注释 set a = 0; end if; ... end;
8. 不能在 MySQL 存储过程当中使用 “return” 关键字。
set c = a + b; select c as sum; /* return c; -- 不能在 MySQL 存储过程当中使用。return 只能出如今函数中。 */ end;
9. 调用 MySQL 存储过程时候,须要在过程名字后面加“()”,即便没有一个参数,也须要“()”
call pr_no_param();
10. 由于 MySQL 存储过程参数没有默认值,因此在调用 MySQL 存储过程时候,不能省略参数。能够用 null 来替代。