mysql存储过程

来源:互联网 发布:域名要实名认证吗 编辑:程序博客网 时间:2024/06/06 14:07

mysql存储过程


一、MySQL 创建存储过程

“pr_add” 是个简单的 MySQL 存储过程,这个MySQL 存储过程有两个 int 类型的输入参数 “a”、“b”,返回这两个参数的和。

  1. drop procedure if exists pr_add;  

计算两个数之和

  1. create procedure pr_add   
  2.   
  3. int,   
  4. int   
  5.   
  6. begin   
  7. declare int;   
  8. if is null then   
  9. set a 0  
  10. end if;   
  11. if is null then   
  12. set b 0  
  13. end if;   
  14. set c a b;   
  15. select as sum;   
  16.    
  17. end;  

二、调用 MySQL 存储过程

  1. call pr_add(10, 20);  

执行 MySQL 存储过程,存储过程参数为 MySQL 用户变量。

  1. set @a 10  
  2. set @b 20  
  3. call pr_add(@a, @b);  

三、MySQL 存储过程特点

创建 MySQL 存储过程的简单语法为:

  1. create procedure 存储过程名字()   
  2.   
  3. [in|out|inout] 参数 datatype   
  4.   
  5. begin   
  6. MySQL 语句;   
  7. end;  

MySQL 存储过程参数如果不显式指定“in”、“out”、“inout”,则默认为“in”。习惯上,对于是“in” 的参数,我们都不会显式指定。

1. MySQL 存储过程名字后面的“()”是必须的,即使没有一个参数,也需要“()”

2. MySQL 存储过程参数,不能在参数名称前加“@”,如:“@a int”。下面的创建存储过程语法在 MySQL 中是错误的(在 SQL Server 中是正确的)。 MySQL 存储过程中的变量,不需要在变量名字前加“@”,虽然 MySQL 客户端用户变量要加个“@”。

  1. create procedure pr_add   
  2.   
  3. @a int, -- 错误   
  4. int -- 正确   
  5.  

3. MySQL 存储过程的参数不能指定默认值。

4. MySQL 存储过程不需要在 procedure body 前面加 “as”。而 SQL Server 存储过程必须加 “as” 关键字。

  1. create procedure pr_add   
  2.   
  3. int,   
  4. int   
  5.   
  6. as -- 错误,MySQL 不需要 “as”   
  7. begin   
  8. mysql statement ...;   
  9. end;  

5. 如果 MySQL 存储过程中包含多条 MySQL 语句,则需要 begin end 关键字。

  1. create procedure pr_add   
  2.   
  3. int,   
  4. int   
  5.   
  6. begin   
  7. mysql statement ...;   
  8. mysql statement ...;   
  9. end;  

6. MySQL 存储过程中的每条语句的末尾,都要加上分号 “;”

  1. ...   
  2. declare int;   
  3. if is null then   
  4. set a 0  
  5. end if;   
  6. ...   
  7. end;  

7. MySQL 存储过程中的注释。

  1.    
  2. declare int; -- 这是单行 MySQL 注释 (注意 -- 后至少要有一个空格)   
  3. if is null then 这也是个单行 MySQL 注释   
  4. set a 0  
  5. end if;   
  6. ...   
  7. end;  

8. 不能在 MySQL 存储过程中使用 “return” 关键字。

  1. set c a b;   
  2. select as sum;   
  3.    
  4. end;  

9. 调用 MySQL 存储过程时候,需要在过程名字后面加“()”,即使没有一个参数,也需要“()”

  1. call pr_no_param();  

10. 因为 MySQL 存储过程参数没有默认值,所以在调用 MySQL 存储过程时候,不能省略参数。可以用 null 来替代。

0 0
原创粉丝点击