MySQL---資料庫從入門走上大神系列(四)-預存程序

來源:互聯網
上載者:User

標籤:

本篇部落格講解:
自動成長列、欄位值唯一性限制式、預存程序、區分大小寫查詢!

自動成長列、欄位值唯一性限制式
create table aa(    id int auto_increment primary key,    sname varchar(32) unique);insert into aa values(5,‘abc‘);

建立一個自動成長的id屬性(最開始不設定就從0開始增長)
(後面的id如果有值了,如果添加資料時沒有設定id,MySQL就會用最大的id加1做為最新的id)
注意:auto_increment 在MySQL中支援,其他的資料庫設定自動成長列中關鍵字不一樣。
unique 對sname進行唯一性限制式,也就是不能有相同的sname(可以有一個值是null)。

預存程序:

其實這個SQL中的預存程序很像Java中的定義函數,調用函數。

首先看定義:

create procedure 過程名(參數...)begin    SQL語句...end

調用:

call 過程名(實參)

有一個需要注意的地方:
在定義前,需要先把預設的語句結束’;’號改成其它,如’&&’,這樣預存程序中定義的分號就不會被看成是語句結束(否則會直接被提交)。
在定義完之後,還要把’;’還原成預設的結束符。

執行個體一:無參的預存程序
delimiter &&create procedure p1()begin    insert into stud values(‘P100‘,‘小李‘,43);    select * from stud;end&&delimiter ;call p1;/*調用p1()中的SQL語句,如果沒有call之前,p1()中的SQL語句是沒有被執行的*/

執行個體二:有參的預存程序
delimiter &&create procedure p2(in id varchar(32),in sname varchar(32),in age int)begin    insert into stud values(id,sname,age);    select * from stud;end &&delimiter ;call p2(‘P1007‘,‘小白‘,25);call p2(‘P1008‘,‘小麗‘,28);
執行個體三:有傳回值的預存程序
delimiter &&create procedure p3(in id varchar(32) ,in sname varchar(32),in age int ,out num int)begin    insert into stud values(id,sname,age);    select * from stud;    select count(*) into num from stud;end&&delimiter ;call p3(‘P012‘,‘小小五‘,27, @num);/*調用且用num接收結果*/select @num; /*顯示使用者變數num*/

系統變數名稱:@@變數名
使用者變數名稱:@變數名

區分大小寫查詢:

因為MySQL的查詢是預設不區分大小寫:
如果有些時候需要區分大小寫,我們就需要binary這個關鍵字了。
可以這樣用,在stud表中尋找sname中帶’j’ /’J’:
先不寫binary進行查詢:

select * from stud where sname like ‘J%‘;

寫binary進行查詢:

select * from stud where binary sname like ‘J%‘;

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.