資料庫之儲存過程和儲存函式 六

2021-09-26 14:21:33 字數 2860 閱讀 3436

​ 儲存過程是一組為了完成某項特定功能的sql語句集,其實質就是一段儲存在資料庫中的**。它可以由宣告式的sql語句和過程式sql語句組成。

1. 可以增強sql語言的功能和靈活性 

2. 良好的封裝性

3. 高效能

4. 減少網路流量

5. 可作為一種安全機制來確保資料庫的安全性和資料的完整性

-- 自定義結束符$$

delimiter $$

-- 建立儲存過程

create procedure sp_name([proc_parameter[,…]]) -- sp_name儲存過程的名稱

routine_body -- 儲存過程的主體部分,也稱為儲存過程體

-- 例:

create procedure sp_update_***(in cid int,in c*** char(1))

begin

update customers set cust_***=c*** where cust_id=cid;

end $$

-- 使用declare語句宣告區域性變數

declare var_name[,…] type [default value]

例:declare var_name[,…] type [default value]

-- 使用declare語句宣告區域性變數

1)只能在儲存過程體的begin…end語句塊中宣告;

2)必須在儲存過程的開頭處宣告;

3)作用範圍僅限於宣告它的begin…end語句塊;

4)不同於使用者變數

區域性變數與使用者變數的區別:

1)區域性變數宣告時,在其前面沒有@符號,並且它只能

​ 被宣告它的begin…end語句塊中的語句所使用;

2)使用者變數在宣告時,會在其名稱前面使用@符號,同

​ 時已宣告的使用者變數存在於整個會話之中。

-- 使用set語句為區域性變數賦值

set var_name=expr[,var_name=expr]…

例:set cid=910;

-- 使用select…into語句把選定列的值直接儲存到區域性變數中

select col_name[,…] into var_name[,…] table_expr

1、條件判斷語句

if 條件 then 表示式1 else 表示式2 end if

case語句

2、迴圈語句

while語句

例: while 條件 表示式 end while

repeat語句

例:repeat 表示式 end repeat

loop語句

例:loop 表示式 end loop

3、結束語句

iterate語句 -- 用於表示退出當前迴圈

4、使用declare cursor語句建立游標

declare cursor_name cursor for select_statement

5、使用open語句開啟游標

open cursor_name

6、使用fetch…into語句讀取資料

fetch cursor_name into var_name[,var_name] …

7、使用close語句關閉游標

close cursor_name

8、使用call語句呼叫儲存過程

call sp_name([parameter[,…]])

call sp_name[()]

例:> call sp_update_***(909,』m』);

9、使用drop procedure語句刪除儲存過程

drop procedure[if exists] sp_name

儲存函式與儲存過程一樣,是由sql語句和過程式語句組成的**片段。

create function sp_name([func_parameter[,…]]) 

returns type -- 宣告儲存函式返回值的資料型別; type指定返回值的資料型別

routine_body -- 指定儲存函式的主體部分,也稱為儲存函式體

例: use mysql_test;

delimiter $$

create function fn_search(cid int) returns char(20)

deterministic

begin

declare *** char(20);

select cust_*** into *** from customers where cust_id=cid;

if *** is null then return(select』沒有該客戶』);

else if ***=『f』 then return(select』女』);

else return(select 『男』);

end if;

end if; end $$

select sp_name([func_parameter[,…]])
drop function [if exists] sp_name
儲存函式

儲存過程

不能擁有輸出引數

可以擁有輸出引數

必須包含一條return語句

不允許包含return語句

可以直接呼叫儲存函式,不需要call語句

需要call語句呼叫儲存過程

Oracle資料庫儲存過程和儲存函式

指儲存在資料庫中供所有使用者程式呼叫的子程式叫儲存過程 儲存函式。儲存過程沒有返回值。儲存函式有返回值 建立儲存過程 用create procedure命令建立儲存過程和儲存函式。語法 create or replace procedure過程名 引數列表 as plsql子程式體 儲存過程示例 為...

資料庫程式設計 儲存過程和儲存函式

一,儲存過程的基本概念 儲存過程是一組為了完成某項特定功能的sql語句集,其實質上就是一段儲存在資料庫中的 他是由宣告式sql語句 如create,uopdate,seletct等語句 和過程式sql語句 如if then else控制結構語句 組成。這組語句集經過編譯後會儲存在資料庫中,使用者只需...

九 資料庫之儲存過程和函式

create procedure 儲存過程名 引數模式 引數名 引數型別 begin 儲存過程體 endcall 儲存過程名 實參列表 建立並呼叫空參列表 建立 delimiter create procedure myp1 begin insert into admin username,pass...