> 데이터 베이스 > MySQL 튜토리얼 > MySql存储过程的问题_MySQL

MySql存储过程的问题_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
풀어 주다: 2016-06-01 13:42:10
원래의
1163명이 탐색했습니다.

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

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿