1. 程式人生 > >11)-MySQL存儲過程

11)-MySQL存儲過程

lar 函數名 number ice cts bsp 執行 span average

創建存儲過程


create procedure productpricing() #定義存儲過程函數名稱 begin #存儲開始 select avg(prod_price) as priceaverage from products; #MySQL語句 end; #結束 shell模式下執行mysql語句註意:分隔符
delimiter // create procedure productpricing() begin select avg(prod_price) as priceaverage from products; end // delimiter ; DELIMITER//告訴命令行實用程序使用//作為新的語句結束分隔符 可以看到標誌存儲過程結束的END定義為END//而不是END; 這樣,存儲過程體內的;仍然保持不動,並且正確地傳遞給數據庫引擎。 最後,為恢復為原來的語句分隔符,可使用DELIMITER;。 調取存儲過程
call avg_student() #通過關鍵詞call調取存儲過程名稱 # 因為存儲過程實際上是一種函數,所以存儲過程名後需要有()符號(即使不傳遞參數也需要)。

刪除存儲過程


drop procedure productpricing; 這條語句刪除剛創建的存儲過程。請註意沒有使用後面的(),只給出存儲過程名。

檢查存儲過程

show create procedure ordertotal; 存儲過程例子(1)
create procedure ordertotal( in onumber int, #in 用來接收用戶輸入 out ototal decimal(8,2) #out用來返回用戶輸入 ) begin select sum(item_price*quantity) from orderitems where order_num = onumber into ototal; #into用來接收值 end; 調取
CALL ordertotal(20005, @total);
存儲過程例子(2) create procedure ordertotal( in onumber int, #接收用戶值 in taxable boolean, out ototal decimal(8,2) #返回值 ) begin declare total decimal(8,2); #定義局部變量 declare taxrate int default 6; #定義局部變量 select sum(item_price*quantity) from orderitems where order_num = onumber into total; #存儲值 if taxable then #if判斷 select total+(total/100*taxrate) into total; end if; select total into ototal; end; 調取
call ordertotal(20005, 0, @total); select @total;

11)-MySQL存儲過程