SQL Server中類似Oracle中before觸發器

來源:互聯網
上載者:User

有這樣的應用情形,除了使用2表之間主外鍵約束中啟用級聯修改和串聯刪除這種SQL Server內建的解決方案外,我們還可以使用觸發器來完成類似的功能,以下通過一個刪除來舉例說明:

 

假如一個SysFuncDic(功能字典表)、SysFuncRights(功能許可權表),功能許可權表中的FuncID和功能字典表中FuncID有外鍵約束關係,現在我們要刪除SysFuncDic中的記錄,因為做過外鍵約束關係,所以無法刪除。解決的辦法是首先刪除SysFuncRights表中所有與FuncID對應的記錄即可。

 

create table SysFuncDic(  FuncID int not null identity(1,1) primary key,  FuncName varchar(100))create table SysFuncRights(   ID int not null primary key identity(1,1),   FuncID int not null,   EmpID int not null)insert into SysFuncDic values('AA')insert into SysFuncDic values('BB')insert into SysFuncDic values('CC')insert into SysFuncRights values(1,12)insert into SysFuncRights values(2,12)insert into SysFuncRights values(3,12)/***********************刪除觸發器**************************/create trigger tri_delete on SysFuncDicinstead of deleteasbegin  declare @FuncID int;  select @FuncID = FuncID  from deleted;  delete SysFuncDic where FuncID = @FuncID;  delete SysFuncRights where FuncID = @FuncID;end/**********************************************************/select * from SysFuncDic; --查詢功能字典表記錄select * from SysFuncRights; --查詢功能許可權表中記錄delete from SysFuncDic where FuncID=1; --刪除功能字典表中記錄,進行測試

聯繫我們

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