將下面的語句復制粘貼可以一次性執行完,我已經測試過,沒有問題!
MySql存儲過程簡單實例:
/********************* 創建表 *****************************/
delimiter // DROP TABLE if exists test // CREATE TABLE test( id int(11) NULL ) //
/********************** 最簡單的一個存儲過程 **********************/
drop procedure if exists sp// CREATE PROCEDURE sp() select 1 // call sp()//
/********************* 帶輸入參數的存儲過程 *******************/
drop procedure if exists sp1 // create procedure sp1(in p int) comment 'insert into a int value' begin /* 定義一個整形變量 */ declare v1 int; /* 將輸入參數的值賦給變量 */ set v1 = p; /* 執行插入操作 */ insert into test(id) values(v1); end // /* 調用這個存儲過程 */ call sp1(1)// /* 去數據庫查看調用之后的結果 */ select * from test//
/****************** 帶輸出參數的存儲過程 ************************/
drop procedure if exists sp2 // create procedure sp2(out p int) /*這里的DETERMINISTIC子句表示輸入和輸出的值都是確定的,不會再改變.我一同事說目前mysql並沒有實現該功能,因此加不加都是NOT DETERMINISTIC的*/ DETERMINISTIC begin select max(id) into p from test; end // /* 調用該存儲過程,注意:輸出參數必須是一個帶@符號的變量 */ call sp2(@pv)// /* 查詢剛剛在存儲過程中使用到的變量 */ select @pv//
/******************** 帶輸入和輸出參數的存儲過程 ***********************/
drop procedure if exists sp3 // create procedure sp3(in p1 int , out p2 int) begin if p1 = 1 then /* 用@符號加變量名的方式定義一個變量,與declare類似 */ set @v = 10; else set @v = 20; end if; /* 語句體內可以執行多條sql,但必須以分號分隔 */ insert into test(id) values(@v); select max(id) into p2 from test; end // /* 調用該存儲過程,注意:輸入參數是一個值,而輸出參數則必須是一個帶@符號的變量 */ call sp3(1,@ret)// select @ret//
/***************** 既做輸入又做輸出參數的存儲過程 ***************************************/
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)// /* 這里需要先設置一個已賦值的變量,然后再作為參數傳入 */ set @pp = 4// call sp4(@pp)//
/********************************************************/