mysql視圖/存儲過程/觸發(fā)器

視圖

視圖是一種虛擬表,只保存查詢的Sql的邏輯
- 創(chuàng)建
create (or replace)view 視圖名 as 查詢語句 #修改視圖
create view user_v as select user,host from mysql.user;
- 查詢視圖

show create view user_v;
select * from user_v where user='song';
-刪除視圖
drop view if exists user_v;

存儲過程

事先經(jīng)過編譯并存儲在數(shù)據(jù)庫中的一段SQL語句集合
#創(chuàng)建
delimiter $$
create procedure p1()
begin
    select count(*) from student;
end$$
delimiter ;
#調(diào)用
call p1();
#查看某個表的存儲過程
select * from information_schema.routines where routine_schema='world';
#查看某個存儲過程的創(chuàng)建語句
show create procedure p1;
#刪除
drop procedure p1;
存儲過程
變量
系統(tǒng)變量:全局變量global 會話變量session
-- 查看系統(tǒng)變量
show session variables ;

show session variables like 'auto%';
show global variables like 'auto%';

select @@global.autocommit;
select @@session.autocommit;
--用戶自定義變量
set @num:='select count(*) from ctiy';
select count(*) into @sum from city; # 將查詢結(jié)果賦值
select @num;
select @sum;
-- 局部變量

create procedure  p3()
begin
    declare s_count int default 3;
        set s_count=5;
    
        select s_count;
end;

call p3();
--if 條件語句

create procedure p3()
begin
    declare score int default 58;
    declare result varchar(10);

    if score >= 85 then
        set result := '優(yōu)秀';
    elseif score >= 60 then
        set result := '及格';
    else
        set result := '不及格';
    end if;
    select result;
end;

-- in/out/inout參數(shù)

-- 根據(jù)傳入(in)參數(shù)score活孩,判定當(dāng)前分?jǐn)?shù)對應(yīng)的分?jǐn)?shù)等級扇商,并返回(out)侥锦。
-- score >= 85分病毡,等級為優(yōu)秀祭务。
-- score >= 60分 且 score < 85分镀迂,等級為及格丁溅。
-- score < 60分,等級為不及格探遵。

create procedure p4(in score int, out result varchar(10))
begin
    if score >= 85 then
        set result := '優(yōu)秀';
    elseif score >= 60 then
        set result := '及格';
    else
        set result := '不及格';
    end if;
end;

call p4(18, @result);


-- 將傳入的 200分制的分?jǐn)?shù),進(jìn)行換算,換算成百分制 , 然后返回分?jǐn)?shù) ---> inout
create procedure p5(inout score double)
begin
    set score := score * 0.5;
end;

set @score = 198;
call p5(@score);
select @score;


-- case
-- 根據(jù)傳入的月份窟赏,判定月份所屬的季節(jié)(要求采用case結(jié)構(gòu))。
-- 1-3月份箱季,為第一季度
-- 4-6月份涯穷,為第二季度
-- 7-9月份,為第三季度
-- 10-12月份藏雏,為第四季度

create procedure p6(in month int)
begin
    declare result varchar(10);

    case
        when month >= 1 and month <= 3 then
            set result := '第一季度';
        when month >= 4 and month <= 6 then
            set result := '第二季度';
        when month >= 7 and month <= 9 then
            set result := '第三季度';
        when month >= 10 and month <= 12 then
            set result := '第四季度';
        else
            set result := '非法參數(shù)';
    end case ;


-- while   計算從1累加到n的值拷况,n為傳入的參數(shù)值。

-- A. 定義局部變量, 記錄累加之后的值;
-- B. 每循環(huán)一次, 就會對n進(jìn)行減1 , 如果n減到0, 則退出循環(huán)
create procedure p7(in n int)
begin
    declare total int default 0;

    while n>0 do
         set total := total + n;
         set n := n - 1;
    end while;

    select total;
end;

call p7(100);
--repeat
repeat
  語句
until 條件
end repeat;
--loop
 sum:loop
        if n<=0 then
            leave sum;
        end if;

        if n%2 = 1 then
            set n := n - 1;
            iterate sum;
        end if;

        set total := total + n;
        set n := n - 1;
    end loop sum;

    select total;

-- 游標(biāo)
-- 根據(jù)傳入的參數(shù)uage掘殴,來查詢用戶表 tb_user中赚瘦,所有的用戶年齡小于等于uage的用戶姓名(name)和專業(yè)(profession),
-- 并將用戶的姓名和專業(yè)插入到所創(chuàng)建的一張新表(id,name,profession)中奏寨。

-- 邏輯:
-- A. 聲明游標(biāo), 存儲查詢結(jié)果集
-- B. 準(zhǔn)備: 創(chuàng)建表結(jié)構(gòu)
-- C. 開啟游標(biāo)
-- D. 獲取游標(biāo)中的記錄
-- E. 插入數(shù)據(jù)到新表中
-- F. 關(guān)閉游標(biāo)

create procedure p11(in uage int)
begin
    declare uname varchar(100);
    declare upro varchar(100);
    declare u_cursor cursor for select name,profession from tb_user where age <= uage;
    declare exit handler for SQLSTATE '02000' close u_cursor;

    drop table if exists tb_user_pro;
    create table if not exists tb_user_pro(
        id int primary key auto_increment,
        name varchar(100),
        profession varchar(100)
    );

    open u_cursor;
    while true do
        fetch u_cursor into uname,upro;
        insert into tb_user_pro values (null, uname, upro);
    end while;
    close u_cursor;

end;


call p11(30);






create procedure p12(in uage int)
begin
    declare uname varchar(100);
    declare upro varchar(100);
    declare u_cursor cursor for select name,profession from tb_user where age <= uage;
#條件處理程序
    declare exit handler for not found close u_cursor;

    drop table if exists tb_user_pro;
    create table if not exists tb_user_pro(
        id int primary key auto_increment,
        name varchar(100),
        profession varchar(100)
    );

    open u_cursor;
    while true do
        fetch u_cursor into uname,upro;
        insert into tb_user_pro values (null, uname, upro);
    end while;
    close u_cursor;

end;


call p12(30);


-- 存儲函數(shù)
-- 從1到n的累加

create function fun1(n int)
returns int deterministic
begin
    declare total int default 0;

    while n>0 do
        set total := total + n;
        set n := n - 1;
    end while;

    return total;
end;


select fun1(50);


觸發(fā)器

-- 觸發(fā)器
-- 需求: 通過觸發(fā)器記錄 user 表的數(shù)據(jù)變更日志(user_logs) , 包含增加, 修改 , 刪除 ;

-- 準(zhǔn)備工作 : 日志表 user_logs
create table user_logs(
id int(11) not null auto_increment,
operation varchar(20) not null comment '操作類型, insert/update/delete',
operate_time datetime not null comment '操作時間',
operate_id int(11) not null comment '操作的ID',
operate_params varchar(500) comment '操作參數(shù)',
primary key(id)
)engine=innodb default charset=utf8;

-- 插入數(shù)據(jù)觸發(fā)器
create trigger tb_user_insert_trigger
after insert on tb_user for each row
begin
insert into user_logs(id, operation, operate_time, operate_id, operate_params) VALUES
(null, 'insert', now(), new.id, concat('插入的數(shù)據(jù)內(nèi)容為: id=',new.id,',name=',new.name, ', phone=', NEW.phone, ', email=', NEW.email, ', profession=', NEW.profession));
end;

-- 查看
show triggers ;

-- 刪除
drop trigger tb_user_insert_trigger;

-- 插入數(shù)據(jù)到tb_user
insert into tb_user(id, name, phone, email, profession, age, gender, status, createtime) VALUES (26,'三皇子','18809091212','erhuangzi@163.com','軟件工程',23,'1','1',now());

-- 修改數(shù)據(jù)觸發(fā)器
create trigger tb_user_update_trigger
after update on tb_user for each row
begin
insert into user_logs(id, operation, operate_time, operate_id, operate_params) VALUES
(null, 'update', now(), new.id,
concat('更新之前的數(shù)據(jù): id=',old.id,',name=',old.name, ', phone=', old.phone, ', email=', old.email, ', profession=', old.profession,
' | 更新之后的數(shù)據(jù): id=',new.id,',name=',new.name, ', phone=', NEW.phone, ', email=', NEW.email, ', profession=', NEW.profession));
end;

show triggers ;

update tb_user set profession = '會計' where id = 23;

update tb_user set profession = '會計' where id <= 5;

-- 刪除數(shù)據(jù)觸發(fā)器
create trigger tb_user_delete_trigger
after delete on tb_user for each row
begin
insert into user_logs(id, operation, operate_time, operate_id, operate_params) VALUES
(null, 'delete', now(), old.id,
concat('刪除之前的數(shù)據(jù): id=',old.id,',name=',old.name, ', phone=', old.phone, ', email=', old.email, ', profession=', old.profession));
end;

show triggers ;

delete from tb_user where id = 26;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末起意,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子病瞳,更是在濱河造成了極大的恐慌揽咕,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件套菜,死亡現(xiàn)場離奇詭異亲善,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)逗柴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進(jìn)店門逗爹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人嚎于,你說我怎么就攤上這事掘而。” “怎么了于购?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵袍睡,是天一觀的道長。 經(jīng)常有香客問我肋僧,道長斑胜,這世上最難降的妖魔是什么控淡? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮止潘,結(jié)果婚禮上掺炭,老公的妹妹穿的比我還像新娘。我一直安慰自己凭戴,他們只是感情好涧狮,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著么夫,像睡著了一般者冤。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上档痪,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天涉枫,我揣著相機(jī)與錄音,去河邊找鬼腐螟。 笑死愿汰,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的乐纸。 我是一名探鬼主播衬廷,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼锯仪!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起趾盐,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤庶喜,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后救鲤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體久窟,經(jīng)...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年本缠,在試婚紗的時候發(fā)現(xiàn)自己被綠了斥扛。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡丹锹,死狀恐怖稀颁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情楣黍,我是刑警寧澤匾灶,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站租漂,受9級特大地震影響阶女,放射性物質(zhì)發(fā)生泄漏颊糜。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一秃踩、第九天 我趴在偏房一處隱蔽的房頂上張望衬鱼。 院中可真熱鬧,春花似錦憔杨、人聲如沸鸟赫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽惯疙。三九已至,卻和暖如春妖啥,著一層夾襖步出監(jiān)牢的瞬間霉颠,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工荆虱, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蒿偎,地道東北人。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓怀读,卻偏偏與公主長得像诉位,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子菜枷,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,627評論 2 350

推薦閱讀更多精彩內(nèi)容