Mysql預存程序和函數

來源:互聯網
上載者:User

標籤:declare   銀行   one   sql   hone   rom   判斷   set   cti   

Mysql預存程序和函數
  1. 基本概念:

  建立預存程序和函數是指將經常使用的一組SQL語句的組合在一起,並將這些SQL語句當作一個整體儲存在MySQL伺服器中。例如,銀行經常需要計算使用者的利息。不同類別的使用者的利率是不一樣的。這就可以將計算利率的SQL代碼寫成一個預存程序或者儲存函數。只要調用這個預存程序或者儲存函數,就可以將不同類別使用者的利息計算出來。

  1. 建立預存程序

delimiter $$;

create procedure 名稱(參數列表)

begin

SQL語句塊

end

$$;

delimiter;

  1. 預存程序中變數的定義、參數類型和傳參

變數定義:–declare 變數名 資料類型 default 預設值

參數類型:

   –in參數:表示該參數的值必須在調用預存程序之前指定,在預存程序中修改的值不能被返回,也就是調用的時候就得指定,預設傳入的就是in參數

   舉例:

   –out參數:該值可在預存程序內部改變,並可以返回.往往是用於擷取預存程序裡的參數值。

   –inout參數:該值可以在調用時指定,並可修改和返回。

傳參:–create procedure test_p( in 參數名 參數類型,out 參數名 參數類型)

   舉例:

delimiter $$;

create procedure test_p8(id int,out phone int,inout s_name varchar(20))

begin

declare sex varchar(10) default ‘男‘;

set id = id+1;

set phone = 186125312;

select s_name;

set s_name = ‘BESTTEST‘;

insert into students values (id,s_name,phone,sex);

end

$$;

delimiter;

set @phone=99888;

set @s_name=‘besttest‘

call test_p8(70,@phone,@s_name);

select * from students;

     select @s_name;

  1. 預存程序中語句

1)         if條件判斷:

if 條件 then

語句

elseif 條件 then

語句

else

語句

        end if;

2)         case條件判斷:

case value

when 條件 then

sql語句

when 條件2 then

sql語句

else#如果上麵條件都不滿足的話執行

sql語句

        end case

3)         while迴圈:

while 條件 do

sql語句

        end while;

4)         repeat迴圈:

repeat

sql語句

until 條件

        end repeat;

  1. 建立函數

函數和預存程序類似,區別是函數有傳回值,預存程序沒有傳回值。

create function 函數名( 變數1,變數2.....)

returns 資料類型

begin

......執行的程式碼

return 資料;

     end;

  1. 查看預存程序和函數

show procedure status;

show function status;

show create procedure;

show create

  1. 刪除預存程序或函數

drop { procedure| function } sp_name;

Mysql預存程序和函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.