我的第一個觸發器練習

來源:互聯網
上載者:User

表ExA如下:
CREATE TABLE ExA (
 id int IDENTITY (1, 1) NOT NULL ,
 status bit NULL ,
 primary key (id)
)
select * from ExA
id          status
----------- ------
4           1
6           1

 

表ExB如下:
CREATE TABLE ExB (
 id int IDENTITY (1, 1) NOT NULL ,
 Aid int NULL ,
 mark varchar (50)  NULL ,
 primary key (id),
 foreign key (Aid) references ExA On Delete Cascade On Update Cascade
)
select * from ExB
id          Aid         mark                                              
----------- ----------- --------------------------------------------------
76          4           test1
77          4           test2
78          4           test3
79          4           test4
84          6           test1
85          6           test2
86          6           test3
87          6           test4

ExA.id與ExB.Aid是一對多的關係。

現在要求,當ExB中刪除記錄時,檢查表,若ExA的資料在ExB中沒有找到對應的資料,則將ExA.Status設定為0。

觸發器如下:
Alter Trigger trTestEx
On ExB
For Delete
As
Declare curDelete cursor for
 select Aid from Deleted group by Aid
Declare @intAid int
Open curDelete
Fetch Next from curDelete Into @intAid
while @@Fetch_Status=0
Begin
 if exists(select * from ExA where id=@intAid)
 Begin
  if not exists(select * from ExB where Aid=@intAid)
   Update ExA set status=0 where id=@intAid
 End
 Fetch Next from curDelete Into @intAid
End
Close curDelete
Deallocate curDelete
Go

Delete From ExB where Aid=4   --支援Delete From ExB where Aid in (4,6) 
結果如下:

select * from ExA
id          status
----------- ------
4           0
6           1
select * from ExB
id          Aid         mark                                              
----------- ----------- --------------------------------------------------
84          6           test1
85          6           test2
86          6           test3
87          6           test4

聯繫我們

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