1. 程式人生 > >MySQL儲存過程寫法總結

MySQL儲存過程寫法總結

1、建立無參儲存過程。

create procedure product()

begin

        select * from user;

end;

一條簡單的儲存過程建立語句,此時呼叫的語句為:

call procedure();

##注意,如果是在命令列下編寫的話,這樣的寫法會出現語法錯誤,即再select 那一句結束

mysql就會進行解釋了,此時應該先把結尾符換一下:

delimiter //

create procedure product()

begin

        select * from user;

end //

最後再換回來

delimiter ;

2、建立有參儲存過程

有參的儲存包括兩種引數,

一個是傳入引數;

一個是傳出引數;

例如一個儲存過程:

create procedure procedure2(

out p1 decimal(8,2),

out p2 decimal(8,2),

in p3 int

)

begin
select sum(uid) into p1 from user where order_name = p3;
select avg(uid) into p2 from user ;
end ;

從上面sql語句可以看出,p1和p2是用來檢索並且傳出去的值,而p3則是必須有呼叫這傳入的具體值。

看具體呼叫過程:

call product();    //無參

call procedure2(@userSum,@userAvg,201708);    //有參

當用完後,可以直接查詢userSum和userAvg的值:

select @userSum, @userAvg;

結果如下:

+----------+----------+
| @userSum | @userAvg |
+----------+----------+
|    67.00 |     6.09 |
+----------+----------+
1 row in set (0.00 sec)

3、刪除儲存過程

一條語句: drop procedure product;   //沒有括號後面

4、一段完整的儲存過程例項:

-- Name: drdertotal
-- Parameters : onumber = order number
--              taxable = 0 if not taxable,1if taxable
--              ototal = order total variable

create procedure ordertotal(
in onumber int,
in taxable boolean,
out ototal decimal(8,2)
) commit 'Obtain order total, optionally adding tax' 
begin
	-- Declare variable for total
	declare total decimal(8,2);
	-- Declare tax percentage
	declare taxrate int default 6;
	
	--Get the order total
	select Sum(item_price*quantity)
	from orderitems
	where order_num = onumber
	into total;
	
	--Is this taxable?
	if taxable then
		--Yes, so add taxrate to the total
		select total+(total/100*taxrate) into total;
	end if;
	
	--Add finally, save to out variable
	select total into ototal;
end;

上面儲存過程類似於高階語言的業務處理,看懂還是不難的,注意寫法細節

commit關鍵字:它不是必需的,但如果給出,將在show procedure status的結果中給出。

if語句:這個例子給出了mysqlif語句的基本用法,if語句還支援elseif和else子句。

通過show procedure status可以列出所有的儲存過程的詳細列表,並且可以在後面加一個

like+指定過濾模式來進行過濾。