MySQL存儲過程

定義

在一些語言中,有一個概念叫過程'procedure',和函數'function'sql

過程:封裝了若干條語句,調用時,封裝體執行。沒有返回值的函數 函數:有一個返回值的"過程"數據庫

存儲過程:將過程存儲在數據庫中。函數

命令

查看已有的過程:show procedure status
刪除存儲過程: drop procedure if exists procedure_name
調用存儲過程:   call procedure()

語法

1.基礎結構

create procedure procedureName()
begin
  -- 執行的sql
end$

2.變量

存儲過程當中,能夠用declare聲明變量 格式 declare 變量名 變量類型 [default 默認值]code

DELIMITER $; 
create procedure p1()

begin 
    declare age int default 18;
    declare height int default 180;
    select concat(age, '::', height) from dual;
end$

運算

DELIMITER $; 
create procedure p2()
begin
    declare age int default 18;
    declare height int default 180;
    set age:= age+1;
    select age from dual;
end$

引入表達式

DELIMITER $; 
create procedure p3()
begin
    declare age int default 18;
    if age> 18 then
        select '已成年' from dual;
    else
        select '未成年' from dual;
    end if;
end$

存儲過程傳值

存儲過程能夠傳遞參數 格式: [in| out| inout] 參數名 參數類型io

DELIMITER $; 
create procedure p4(age int)
begin
     if age> 18 then
        select '已成年' from dual;
    elseif age = 18 then
        select '正好成年' from dual;
    else 
        select '未成年' from dual;
    end if;
end$

循環結構

DELIMITER $;
CREATE PROCEDURE p5(n INT)
BEGIN
DECLARE total INT DEFAULT 0;
DECLARE num INT DEFAULT 0;
WHILE num < n DO 
	SET num := num + 1;
	SET total := total + num;
END WHILE;
SELECT total FROM DUAL;
END$

輸出型參數

in 輸入function

out 輸出基礎

inout 既能輸入也能輸出變量

DELIMITER $;
 CREATE PROCEDURE p7(IN n INT, OUT total INT)
 BEGIN
	DECLARE num INT DEFAULT 0;
	SET total := 0;
	WHILE num < n DO
		SET num := num + 1;
		SET total := total + num;
	END WHILE;
 END$
 
 CALL p7(100, @total)$
 
 SELECT @total FROM DUAL$
DELIMITER $;
 CREATE PROCEDURE p8(INOUT age INT)
 BEGIN
	SET age := age + 10;
 END$ 
 
 SET @currage = 18$
 
 CALL p8(@currage)$
 
 SELECT @currage $

repeat循環

DELIMITER $;
 CREATE PROCEDURE p10(n INT)
 BEGIN
	DECLARE total INT DEFAULT 0;
	DECLARE num INT DEFAULT 0;	
	REPEAT 
		SET total := total + num;
		SET num := num +1;
	UNTIL num > n END REPEAT;
	SELECT total FROM DUAL;
 END$
 
 CALL p10(100)$
相關文章
相關標籤/搜索