一、MySQL 創(chuàng)建存儲(chǔ)過(guò)程
“pr_add” 是個(gè)簡(jiǎn)單的 MySQL 存儲(chǔ)過(guò)程,這個(gè)存儲(chǔ)過(guò)程有兩個(gè) int 類(lèi)型的輸入?yún)?shù) “a”、“b”,返回這兩個(gè)參數(shù)的和。
drop procedure if exists pr_add;
-- 計(jì)算兩個(gè)數(shù)之和
create procedure pr_add
(
a int,
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 as sum;
/*
return c;- 不能在 MySQL 存儲(chǔ)過(guò)程中使用。return 只能出現(xiàn)在函數(shù)中。
/
end;
二、調(diào)用 MySQL 存儲(chǔ)過(guò)程
call pr_add(10, 20);
執(zhí)行 MySQL 存儲(chǔ)過(guò)程,存儲(chǔ)過(guò)程參數(shù)為 MySQL 用戶(hù)變量。
set @a = 10;
set @b = 20;
call pr_add(@a, @b);
三、MySQL 存儲(chǔ)過(guò)程特點(diǎn)
創(chuàng)建 MySQL 存儲(chǔ)過(guò)程的簡(jiǎn)單語(yǔ)法為:
create procedure 存儲(chǔ)過(guò)程名字()
(
[in|out|inout] 參數(shù) datatype
)
begin
MySQL 語(yǔ)句;
end;
MySQL 存儲(chǔ)過(guò)程參數(shù)如果不顯式指定“in”、“out”、“inout”,則默認(rèn)為“in”。習(xí)慣上,對(duì)于是“in” 的參數(shù),我們都不會(huì)顯式指定。
1. MySQL 存儲(chǔ)過(guò)程名字后面的“()”是必須的,即使沒(méi)有一個(gè)參數(shù),也需要“()”
2. MySQL 存儲(chǔ)過(guò)程參數(shù),不能在參數(shù)名稱(chēng)前加“@”,如:mailto:%E2%80%9C@a int”。下面的創(chuàng)建存儲(chǔ)過(guò)程語(yǔ)法在 MySQL 中是錯(cuò)誤的(在 SQL Server 中是正確的)。 MySQL 存儲(chǔ)過(guò)程中的變量,不需要在變量名字前加“@”,雖然 MySQL 客戶(hù)端用戶(hù)變量要加個(gè)“@”。
create procedure pr_add
(
@a int,- 錯(cuò)誤
b int - 正確
)
3. MySQL 存儲(chǔ)過(guò)程的參數(shù)不能指定默認(rèn)值。
4. MySQL 存儲(chǔ)過(guò)程不需要在 procedure body 前面加 “as”。而 SQL Server 存儲(chǔ)過(guò)程必須加 “as” 關(guān)鍵字。
create procedure pr_add
(
a int,
b int
)
as - 錯(cuò)誤,MySQL 不需要 “as”
begin
mysql statement ...;
end;
5. 如果 MySQL 存儲(chǔ)過(guò)程中包含多條 MySQL 語(yǔ)句,則需要 begin end 關(guān)鍵字。
create procedure pr_add
(
a int,
b int
)
begin
mysql statement 1 ...;
mysql statement 2 ...;
end;
6. MySQL 存儲(chǔ)過(guò)程中的每條語(yǔ)句的末尾,都要加上分號(hào) “;”
...
declare c int;
if a is null then
set a = 0;
end if;
...
end;
7. MySQL 存儲(chǔ)過(guò)程中的注釋。
/*
這是個(gè)
多行 MySQL 注釋。
/
declare c int; - 這是單行 MySQL 注釋 (注意- 后至少要有一個(gè)空格)
if a is null then 這也是個(gè)單行 MySQL 注釋
set a = 0;
end if;
...
end;
8. 不能在 MySQL 存儲(chǔ)過(guò)程中使用 “return” 關(guān)鍵字。
set c = a + b;
select c as sum;
/*
return c;- 不能在 MySQL 存儲(chǔ)過(guò)程中使用。return 只能出現(xiàn)在函數(shù)中。
/
end;
9. 調(diào)用 MySQL 存儲(chǔ)過(guò)程時(shí)候,需要在過(guò)程名字后面加“()”,即使沒(méi)有一個(gè)參數(shù),也需要“()”
call pr_no_param();
10. 因?yàn)?MySQL 存儲(chǔ)過(guò)程參數(shù)沒(méi)有默認(rèn)值,所以在調(diào)用 MySQL 存儲(chǔ)過(guò)程時(shí)候,不能省略參數(shù)??梢杂?null 來(lái)替代。
call pr_add(10, null);
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com