//轉(zhuǎn)載? http://www.cnblogs.com/zhuawang/p/4185302.html
將下面的語句復(fù)制粘貼可以一次性執(zhí)行完,我已經(jīng)測試過,沒有問題!
MySql存儲(chǔ)過程簡單實(shí)例:
/********************* 創(chuàng)建表 *****************************/
delimiter //
DROP TABLE if exists test //
CREATE TABLE test(
id int(11) NULL
) //
/********************** 最簡單的一個(gè)存儲(chǔ)過程 **********************/
drop procedure if exists sp//
CREATE PROCEDURE sp() select 1 //
call sp()//
/********************* 帶輸入?yún)?shù)的存儲(chǔ)過程? *******************/
drop procedure if exists sp1 //
create procedure sp1(in p int)
comment 'insert into a int value'
begin
/* 定義一個(gè)整形變量 */
declare v1 int;
/* 將輸入?yún)?shù)的值賦給變量 */
set v1 = p;
/* 執(zhí)行插入操作 */
insert into test(id) values(v1);
end
//
/* 調(diào)用這個(gè)存儲(chǔ)過程? */
call sp1(1)//
/* 去數(shù)據(jù)庫查看調(diào)用之后的結(jié)果 */
select * from test//
/****************** 帶輸出參數(shù)的存儲(chǔ)過程 ************************/
drop procedure if exists sp2 //
create procedure sp2(out p int)
/*這里的DETERMINISTIC子句表示輸入和輸出的值都是確定的,不會(huì)再改變.我一同事說目前mysql并沒有實(shí)現(xiàn)該功能,因此加不加都是NOT DETERMINISTIC的*/
DETERMINISTIC
begin
select max(id) into p from test;
end
//
/* 調(diào)用該存儲(chǔ)過程,注意:輸出參數(shù)必須是一個(gè)帶@符號(hào)的變量 */
call sp2(@pv)//
/* 查詢剛剛在存儲(chǔ)過程中使用到的變量 */
select @pv//
/******************** 帶輸入和輸出參數(shù)的存儲(chǔ)過程 ***********************/
drop procedure if exists sp3 //
create procedure sp3(in p1 int , out p2 int)
begin
if p1 = 1 then
/* 用@符號(hào)加變量名的方式定義一個(gè)變量,與declare類似 */
set @v = 10;
else
set @v = 20;
end if;
/* 語句體內(nèi)可以執(zhí)行多條sql,但必須以分號(hào)分隔 */
insert into test(id) values(@v);
select max(id) into p2 from test;
end
//
/* 調(diào)用該存儲(chǔ)過程,注意:輸入?yún)?shù)是一個(gè)值,而輸出參數(shù)則必須是一個(gè)帶@符號(hào)的變量 */
call sp3(1,@ret)//
select @ret//
/***************** 既做輸入又做輸出參數(shù)的存儲(chǔ)過程 ***************************************/
drop procedure if exists sp4 //
create procedure sp4(inout p4 int)
begin
if p4 = 4 then
set @pg = 400;
else
set @pg = 500;
end if;
select @pg;
end//
call sp4(@pp)//
/* 這里需要先設(shè)置一個(gè)已賦值的變量,然后再作為參數(shù)傳入 */
set @pp = 4//
call sp4(@pp)//
/********************************************************/