日期:2014-05-16  浏览次数:20700 次

Mysql 存储过程2

4,if 多条件分支

? select * from customer;

? mysql> select * from customer

+----+--------+----------+

| id | name ? | password |

+----+--------+----------+

| ?2 | lijuan | lijuan ? |

| ?3 | 陈超阳 | 陈超阳 ? |

| ?4 | 张三 ? | 张三 ? ? |

| ?5 | 张三 ? | 张三 ? ? |

| ?6 | 李四 ? | 李四 ? ? |

+----+--------+----------+

5 rows in set (0.04 sec)

? create procedure sp_search_customer6(in mycondition int)

? begin

? ? ?if mycondition > 0 then

? ? ? ? ?select * from customer where name = '陈超阳';

? ? ?elseif mycondition > 1 ? ?then

? ? ? ? ?select * from customer where name = '张三';

? ? ?elseif mycondition > 2 ?then

? ? ? ? ?select * from customer where name = '李四';

? ? ?else

? ? ? ? ?select * from customer;

? ? ?end if;

? end

? call sp_search_customer(2);

? 结果:

? ? mysql> call sp_search_customer6(3);

+----+--------+----------+

| id | name ? | password |

+----+--------+----------+

| ?3 | 陈超阳 | 陈超阳 ? |

+----+--------+----------+

1 row in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

? 注意点:1,在多个条件下,如果给出的条件满足多个分支,那么只执行最前面

? ? ? ? ? 的那个条件。上述存储过程只要给出大于0的数结果总是陈超阳。

?说明了那个问题。

?2,elseif 是合体,不能分开。

?3,end if是分体,并且需要跟上分号。

2013/8/19 2258 ?131

?

?

5,mysql中case分支语句。

? create procedure sp_search_cusomer7(in mycondition int)

begin

? case mycondition

? ? ? when 1 then

? ? ? ? ? select * from customer where name = '陈超阳';

? ? ? when 2 then?

? ? ? ? ? select * from customer where name = '张三';

? ? ? when 3 then?

? ? ? ? ? select * from customer where name = '李四';

? ? ? when 4 then

? ? ? ? ? select * from customer where name = '王五';

? ? ? else

? ? ? ? ? select * from customer;

? end case;

end

call sp_search_cusomer7(7);

?

6,本地变量(也叫局部变量

? ?在上一个例子中我们可以看到有很多相似的代码,我们可以吧相似的代码

? ?放在判断条件之外,让可变的地方以变量来表示。对上个存储过程我们

? ?修改为如下结构。

? ?create procedure sp_search_customer8(in mycondition int)

begin?