MySQL存储过程入门

p34f 9年前

以前没用过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并以分号结束。

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