sql中的觸發器、視圖、事務

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   sp   for   strong   資料   

 

·觸發器(trigger)  

【觸發器本質上還是一個預存程序,只不過不是用exe來調用執行,而是通過增刪改資料庫的操作】

【觸發器只對增、刪、改有效】

 

觸發器的格式

(instead of與for的區別 如下)

instead of:

 

create trigger 觸發器名(TR_表名_操作)

on 表名

instead of 增或刪或改

--當為instead of時,go下的代碼不執行只起到觸發的作用,只執行as裡面的代碼

as

   as裡面隨便寫代碼

go

   go下的代碼只能是 增或刪或改

 

 

for:

create trigger 觸發器名(TR_表名_操作)

on 表名

for增或刪或改

--當為for時,go下的代碼先執行操作,再執行as裡面的代碼

as

   as裡面隨便寫代碼

go

   go下的代碼只能是 增或刪或改

 

寫觸發器時,go下面代碼中的增刪改和表名,與on後面的表名instead of或者for後面的增刪改差要一致,否則無法觸發

 

 

例子:(在觸發器中可以有參數)

Instead of實用:

create trigger dongtaichufa

on teacher

instead of delete

as

begin

   declare @tno varchar(20)

   set @tno=(select tno from deleted)--deleted的作用是儲存臨時資料(儲存的是tno為的一行資料),@tno=tno的含義是擷取教師工號

   delete from teacher where [email protected]刪除這一條資料

end

go

delete from teacher where tno= ‘831‘

 

for實用:

create trigger tr_dongtai

on teacher

for insert

as

begin

   declare @tno varchar(20)--定義一個變數

   set @tno=(select tno from inserted)--inserted的作用是臨時儲存資料,(儲存要插入的一行資料),@tno的含義是擷取要插入的教師的編號

   delete from teacher where [email protected] --刪除剛剛插入的一行資料

  

end

go

insert into teacher values(‘810‘,‘王五‘,‘男‘,‘1991-1-1‘,‘講師‘,‘電子工程系‘)

 

 

 

視圖(view)

1、視圖視窗建立視圖步驟:1·資料庫名-->右鍵視圖(建立視圖)-->2·添加要串連的表-->3·選擇要添加的列名

 

 

 

 

【代碼建立視圖】:

   格式為:

   create view 視圖名

as

select 表名.列名,表名.列名,表名.列名,表名.列名 from 表名 join 表名 on 表名.列名=表名.列名

 

--------------例如:

沒用視圖如下

 

用代碼建立視圖為:

create view shitu

as

select student.sno,sname,ssex,sbirthday,class,course.cno,cname,degree,tno from

student join score on student.sno=score.sno join course on score.cno=course.cno

 

 

 

 

 

事務

 

         Begin  tran----開始事務

         Commit---提交

         Rollback---復原事務

---事務(在begin tran裡面有多個代碼,如果有一個發生錯誤,則全部停止,並返回begin tran開始處)

 

執行個體:

 

begin tran--事務的開始

  insert into student values(‘110‘,‘hh‘,‘aa‘,‘1987/1/12‘,5788)     —插入第一個資料為主鍵,110沒有重複的,正確

if @@ERROR >0     --全域變數,判斷上一句中是否有錯,返回0沒有錯,不等於0則發生錯誤

goto tr       --如果發生錯誤,則跳轉到名字為tr的一行(goto後面的只是個名字而已)

  insert into course  values(‘3-105‘,‘電腦‘,825)     --第一個3-105則為外鍵,發生錯誤,表中有3-105

if @@ERROR >0

begin

tr:     --接上面的tr

  rollback tran     --復原到tran開始處

end

else      --如果沒有錯誤的話

begin

  commit tran      --提交事務,接著往下運行

end

 

 

sql中的觸發器、視圖、事務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.