mysql存储过程判断语法_mysql存储过程 基本语法

话不多说

一、MySQL 创建存储过程

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

drop procedure if exists pr_add;

-- 计算两个数之和

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 只能出现在函数中。

/

end;

二、调用Mysql存储过程

eg: call pr_add(10,20);

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

set @a = 10;

set @b = 20;

call pr_add(@a, @b);

三、MySQL 存储过程特点

创建 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;

...

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

/*

这是个

多行 MySQL

你可能感兴趣的:(mysql存储过程判断语法)