mysql-進階 聲明變數/預存程序

來源:互聯網
上載者:User

標籤:

聲明變數

設定全域變數

set @a=‘一個新變數‘;

 

在函數和儲存過程中使用的變數declear

declear a int unsigned default 1;

這種變數需要設定變數類型 而且只存在在 begin..end 這段之內

 

select .. into..  直接將表內內容賦值到指定變數當中

select name,bid into @a,@b from bank limit 1;

要注意一點就是變數名不能和欄位名一致

 

 

預存程序

預存程序將一段通用的操作封裝在一起 這樣再不同平台都可以公用了

儲存過程沒有傳回值,而且不能sql語句調用,只能是call調用,而且不返回結果集,執行就執行了

要注意的是在儲存過程中進行sql語句要用到 ; 這個系統預設結束符 要重新設定成別的,不然在寫過程的一半系統就錯認程式為終止繼而報錯

改變結束命令符為$

delimiter$+斷行符號 或者簡寫成 \d $+斷行符號

 

顯示所有預存程序

show procedure status;

刪除指定預存程序

drop procedure 過程名;

 

預存程序示範

 0 \d $
1 create procedure yanshi(in arg tinyint) 2 begin 3 declare age tinyint default 0; 4 set age=arg; 5 if age<20 then 6 select ‘小於20的數‘; 7 elseif age>20 then 8 select ‘大於20的數‘; 9 end if;10 end11 $12 //調用過程13 set @num=12$14 call yanshi(@num)$15 call yanshi(21)$

判斷輸入到預存程序中的數字屬於哪個階段

 

在預存程序中傳參分 in out inout 三種

 

in 可以輸出從外部傳入的變數 不會改變傳進變數本來的值

create procedure a(in id int)
begin
    select id;
    set id = 100;
end
$
set @id=1$
call a(@id)$  //輸出1 即從外部傳進來的@id 的值

select $id$  //輸出1 說明預存程序中沒有改變傳進的值

 

out 不能輸出從外部傳進的值  會改變傳進變數本來的值

create procedure b(out id int)
begin
    select id;
    set id = 100;
end
$
set @id=1$
call b(@id)$   //輸入null

select @id$ //輸出100

 

inout 就是又能輸出傳入變數又能改變傳入變數咯

 

 

 

下面是檢驗你電腦硬體效能的時候了

還記得當年的bank表嗎? 就是他保留住 然後執行以下命令:

create procedure addbank()
begin
    declare i int default 0;
    set i = 5000000;
    while i > 0 do
    insert into bank (name) values (i);
    set i = i - 1;
    end while;
end
$

call addbank()$

祝你好運

 

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.