存儲過程入門


我們常用的操作數據庫語言SQL語句在執行的時候需要要先編譯,然后執行,而存儲過程(Stored Procedure)是一組為了完成特定功能的SQL語句集,經編譯后存儲在數據庫中,用戶通過指定存儲過程的名字並給定參數(如果該存儲過程帶有參數)來調用執行它。

一個存儲過程是一個可編程的函數,它在數據庫中創建並保存。它可以有SQL語句和一些特殊的控制結構組成。當希望在不同的應用程序或平台上執行相同的函數,或者封裝特定功能時,存儲過程是非常有用的。數據庫中的存儲過程可以看做是對編程中面向對象方法的模擬。它允許控制數據的訪問方式。

簡單來說就是存儲過程就是將若干條sql語句封裝起來,編譯好放在mysql服務器中,需要時調用即可

存儲過程的創建語法

 

create procedure procedureName()
begin
    //sql語句
end

存儲過程是可以編程的,意味着可以使用變量、表達式、控制結構,來完成復雜的功能

1.在存儲過程中,使用declare聲明變量,其格式為:declare 變量名 變量類型 [default 默認值]

例如:

create procedure p1()
begin
    declare age int default 18;
    declare height int default 180;
    select concat('年齡',age,'身高是',height);
end

 2.存儲過程中,變量可以使用sql語句進行合法的運算,如+、-、*、/

  運算結果賦值給變量: set 變量名 := expression(表達式)

create procedure p2()
begin
    declare age int default 18;
    set age := age + 20;
    select concat('20年后年齡是',age);
end

 3.控制結構,與我們平常見到的if、else差不多

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

4.循環結構(while和repeat)

//循環結構
create procedure p4()
begin
    declare num int default 0;
    declare total int default 0;

    while num <=100 do
        set total := total + num;
        set num := num + 1;
    end while;

    select total;
end$

create procedure p5()
begin
    declare i int default 0;
    declare total int default 0;

    repeat
    set i := i + 1;
    set total := total + i;
    until i >= 100 end repeat;

    select total;
end$

5.case結構(類似java的switch)

create procedure p6()
begin
    declare pos int default 0;

    set pos := floor(5*rand());

    case pos
    when 1 then select '還在飛';
    when 2 then select '掉海里了';
    when 3 then select '在小島上';
    else select '我不知道';
    end case;
end$

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM