您好,欢迎访问一九零五行业门户网

MySql存储过程的问题_MySQL

bitscn.com 以前没用过mysql存储过程,第一次写有很多的不习惯,记录如下:  下面是一个最简单的mysql存储过程,实现两个数相加,需要特别注意的是 
 sql代码  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之后必须跟分号,否则语法错误  下面是一个较常见的场景,判断表中某列是否存在某值,如果存在执行某操作 
 sql代码  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的简单应用: 
 sql代码      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并以分号结束。 以上是一些简单的总结,希望有用。  作者 yukaizhao bitscn.com
其它类似信息

推荐信息