7 MySQL預存程序和函數

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

目錄:

1. 預存程序和函數概述
2. 準備工作
3. 預存程序操作
4. 建立帶參預存程序
5. 查看預存程序

 

1. 預存程序和函數概述

  MySQL的預存程序(stored procedure)和函數(stored function)統稱為stored routines。
  預存程序和函數都是事先經過編譯並儲存在資料庫中的一段SQL語句的集合,調用預存程序和函數可以簡化應用開發人員的很多工作,減少資料在資料庫和應用伺服器之間的傳輸。
  預存程序和函數的區別在於函數必須有傳回值,而預存程序沒有,預存程序的參數可以使用IN、OUT、INOUT類型,而函數的參數只能是IN類型。

2. 準備工作(為了提高沒小節的獨立性,該準備工作會在後續指導中反覆用到)

  建立表,摻入資料

  

 1 drop table if exists student; 2  3 create table student ( 4 id int(5) not null, 5 name varchar(20), 6 birthday date 7 ); 8  9 insert into student values(1, ‘guo jing‘, ‘1990-01-01‘);10 insert into student values(2, ‘huang rong‘, ‘1992-02-02‘);11 insert into student values(3, ‘ling hu‘, ‘1993-03-03‘);12 insert into student values(4, ‘dong fang‘, ‘1994-04-04‘);
View Code

 

3. 預存程序操作

  3.1 建立預存程序

  選擇schoolDB資料庫,並在SQL編輯中輸入如下代碼:
create procedure get_young()
begin
select * from student where birthday in (select max(birthday) from student);
end//

(注意更改delimiter為 //)

  

  3.2查看預存程序
show procedure status;

   

  
  
  3.3 在SQL編輯框中調用預存程序

call get_young();
(注意:返回錯誤,目前不清楚如何更改,但經實驗,在MySql Command Line Client中可以成功調用該預存程序。)

  
  3.4 使用MySql Command Line Client調用預存程序

  點擊win7左下開始項,在搜尋方塊中輸入mysql,點擊進入MySql Command Line Client。

  call get_young();
  調用成功。


但在 MySql Command Line Client 中建立預存程序中需注意,因為MySql Command Line Client中需要用語句更改delimiter,mysql中默寫分界符是; ,但select 語句末有;衝突,需要修改分界符。
delimiter //
create procedure get_old()
begin
select * from student where birthday in (select min(birthday) from student);
end//
delimiter ;

   


4. 建立帶參預存程序

在MySQL命令列中輸入
delimiter //
create procedure get_by_year(IN year_in varchar(4))
begin
select * from student where year(birthday)=year_in;
end //
delimiter ;
調用該預存程序
call get_by_year();
返回錯誤,提示需要帶入參數。

  
call get_by_year(1990);
調用成功!

   

5. 查看預存程序

show procedure status;

  
6. 刪除預存程序

drop procedure get_old;

7 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.