MySQL存储历程使用总结_网上的手机数据恢复有用

日期:2014-07-13 / 人气: / 来源:网络

以前没用过MySQL存储过程,第一次写有很多的不习惯,总结如下: 

下面是一个最简单的MySQL存储过程,实现两个数相加

delimiter $$
create procedure proc_add(in a int,in 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;
end$$
delimiter ;

需要特别注意的是 

1. declare语句只能放在存储过程的开始位置,放在后面就会报错 
2. if 语句的后面必须有then,但是不需要begin,在if结束时需要end if 
3. 判断是否为NULL倒是和MSSQL一样都有IS NULL 
4. delimiter是定界符的意思在结束的end后面要添加定界符 
5. end if之后必须跟分号,否则语法错误 

下面是一个较常见的场景,判断表中某列是否存在某值,如果存在执行某操作 

delimiter $$
create procedure proc_add_book(in $bookName varchar(200),in $price float)
begin
    declare $existsFlag int default 0;
    select bookId into $existsFlag from book where bookName = $bookName limit 1;
    if bookId > 0 then
    #if not exists (select * from book where bookNumber = $bookName) then
        insert into book(bookNumber,price) values($bookName,$price);
    end if;
end$$
delimiter ;

需要注意的是不能用if exists;exists可以在where后面或者在create object是使用,但是在if语句中不可以使用,只能用变通的方法。

while语句也需要注意,下面是一个while的简单应用:

delimiter $$
create procedure proc_add_books_looply(in $bookName varchar(200),in $price float,in $insertTimes INT)
begin
    while $insertTimes>0 do
    insert into book (bookName,price) values($bookName,$price);
    end while;
end$$
delimiter ;

可以看到while后面跟条件,条件后面要跟一个do,在while循环体结束之后需要end while并以分号结束。

以上是一些简单的总结,希望有用。

MySQL数据库如何设置双向同步

项目申请了两台数据库服务器,为了保持数据同步,就搞了个数据同步,以此文记录以备后续使用:首先声明:服务器操作系统都是CentOS6.1、mysql版本号一致,为了减少出现其他问题的可能性,故做此环境搭配。数据库服务器A,ip地址:192.168.6.108数据

MySQL教程

作者:管理员




现在致电4006-2991-90 OR 查看更多联系方式 →

Go To Top 回顶部