MySQL存儲過程問題


以前沒用過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並以分號結束。

以上是一些簡單的總結,希望有用。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM