mysql 中的預存程序

來源:互聯網
上載者:User

標籤:limit   drop   toolbar   arc   class   end   png   iter   sele   

建立一個簡單的預存程序

預存程序proc_adder功能很簡單,兩個整型輸入參數a和b,一個整型輸出參數sum,功能就是計算輸入參數a和b的結果,賦值給輸出參數sum;

幾點說明:

DELIMITER ;;:之前說過了,把預設的輸入的結束符;替換成;;。

DEFINER:建立者;

call  : 調用預存程序,用 call 命令

-- ------------------------------ Procedure structure for `proc_adder`-- ----------------------------DROP PROCEDURE IF EXISTS `proc_adder`;DELIMITER ;;CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_adder`(IN a int, IN b int, OUT sum int)BEGIN    #Routine body goes here...    DECLARE c int;    if a is null then set a = 0;     end if;      if b is null then set b = 0;    end if;    set sum  = a + b;END;;DELIMITER ;

  執行以上儲存結果,驗證是否正確,如,結果OK:

set @b=5;call proc_adder(2,@b,@s);select @s as sum;

預存程序中的控制語句

IF語句:

-- ------------------------------ Procedure structure for `proc_if`-- ----------------------------DROP PROCEDURE IF EXISTS `proc_if`;DELIMITER ;;CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_if`(IN type int)BEGIN    #Routine body goes here...    DECLARE c varchar(500);    IF type = 0 THEN        set c = ‘param is 0‘;    ELSEIF type = 1 THEN        set c = ‘param is 1‘;    ELSE        set c = ‘param is others, not 0 or 1‘;    END IF;    select c;END;;DELIMITER ;

CASE語句:

-- ------------------------------ Procedure structure for `proc_case`-- ----------------------------DROP PROCEDURE IF EXISTS `proc_case`;DELIMITER ;;CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_case`(IN type int)BEGIN    #Routine body goes here...    DECLARE c varchar(500);    CASE type    WHEN 0 THEN        set c = ‘param is 0‘;    WHEN 1 THEN        set c = ‘param is 1‘;    ELSE        set c = ‘param is others, not 0 or 1‘;    END CASE;    select c;END;;DELIMITER ;

迴圈while語句:

-- ------------------------------ Procedure structure for `proc_while`-- ----------------------------DROP PROCEDURE IF EXISTS `proc_while`;DELIMITER ;;CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_while`(IN n int)BEGIN    #Routine body goes here...    DECLARE i int;    DECLARE s int;    SET i = 0;    SET s = 0;    WHILE i <= n DO        set s = s + i;        set i = i + 1;    END WHILE;    SELECT s;END;;DELIMITER ;

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.