MySQL知識總結(三)預存程序

來源:互聯網
上載者:User

標籤:

1. 建立預存程序 1.1 無參數預存程序
CREATE PROCEDURE bruce_procedure ()BEGIN--1.聲明變數--2.執行商務邏輯END
1.2 有參數的預存程序
CREATE PROCEDURE bruce_procedure (IN in_exam_id INT,in_student_types_id VARCHAR (100))BEGIN--1.聲明變數--2.執行商務邏輯END

IN 表示輸入參數

2. 調用預存程序
--無參調用Call bruce_procedure();--有參調用Call bruce_procedure(1,’2,1’);
3. 刪除預存程序
Drop procedure bruce_procedure;
4. 查看預存程序資訊

1) show procedure status

顯示資料庫中所有儲存的預存程序基本資料,包括所屬資料庫,預存程序名稱,建立時間等

2) show create procedure sp_name

顯示某一個預存程序的詳細資料

5. 聲明變數
CREATE PROCEDURE sc_st_group_courses_class_procedure (IN in_exam_id INT,in_student_types_id VARCHAR (100))BEGIN-- 組織課程組關係idDECLARE v_group_courses_id INT;-- 考試組織idDECLARE v_exam_group_id INT;END

1) 可以在預存程序全域範圍內聲明

2) 如果要在局部範圍內聲明,需重新定義begin end,並在begin和end之間聲明變數

6. If
if stop = 1 thenleave cur_loop;end if;
7. 迴圈7.1 結構
cur_loop : loop//商務邏輯end loop //結束迴圈
7.2 跳出迴圈

leave cur_loop;

8. 遊標8.1 聲明遊標
CREATE PROCEDURE sc_st_group_courses_class_procedure() BEGIN DECLARE STOP INT DEFAULT 0;-- 建立遊標DECLARE cur CURSOR FOR (selectgroup_courses_id,exam_group_id,courses_id,class_idfrom sc_group_courses_view WHERE group_class=‘class‘ and exam_id = in_exam_id);-- 遊標捕捉越界異常DECLARE CONTINUE HANDLER FOR SQLSTATE ‘02000‘ SET STOP = 1;END
8.2 開啟和關閉遊標

開啟遊標:OPEN cur

關閉遊標:CLOSE cur

8.3 遍曆遊標
CREATE PROCEDURE sc_st_group_courses_class_procedure()BEGIN DECLARE STOP INT DEFAULT 0;-- 建立遊標DECLARE cur CURSOR FOR (selectgroup_courses_id,exam_group_id,courses_id,class_idfrom sc_group_courses_view WHERE group_class=‘class‘ and exam_id = in_exam_id);-- 遊標捕捉越界異常DECLARE CONTINUE HANDLER FOR SQLSTATE ‘02000‘ SET STOP = 1;-- 開啟遊標OPEN cur;-- 開始迴圈cur_loop : loopFETCH cur INTOv_group_courses_id,v_exam_group_id,v_courses_id,v_class_id;-- 判斷遊標溢出if stop = 1 thenleave cur_loop;end if;-- 結束迴圈END loop cur_loop;-- 關閉遊標CLOSE cur;END
9. 給變數賦值

DECLARE v_median_index int;

set v_median_index = v_class_count/2-1;

10. 查詢並賦值給變數
selectmax(sum_score),min(sum_score),avg(sum_score),STD(sum_score)intov_highest_score,v_lowest_score,v_average,v_stdfrom a;
11. 參考

http://www.ccvita.com/100.html

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.