三種類型的觸發器

來源:互聯網
上載者:User

 /* 建三個表分別為
stu.info : stu_id int ,stu_nam char(10) ,stu_tel char(10)
stu_e : stu_id int,stu_hei char(10),sex bit
stu_cj : stu_id int,stu_cj float
*/
--觸發器 insert
if exists(select * from sysobjects where name='T_test1')
begin
 drop Trigger T_test1
end
go
 create Trigger T_test1 on stu_info
for insert
as

declare  @stu_id int,
  @stu_nam char
select
 @stu_id =stu_id,
 @stu_nam =stu_nam
from inserted
 

begin transaction

if not exists (select * from stu_e where stu_id=@stu_id)
begin
 insert stu_e values(@stu_id,'178',1)
end

if not exists (select * from stu_cj where stu_id=@stu_id)
begin
 insert stu_cj values(@stu_id,56.00)
end
commit transaction

insert stu_info values(2,'bb','2222222')

select * from stu_info
select * from stu_e
select * from stu_cj
--------------------------------------------------------------------
--觸發器update
if exists(select * from sysobjects where name='T_test2')
begin
 drop Trigger T_test2
end
go
 create Trigger T_test2 on stu_info
for update
as

begin transaction
if update(stu_id)
 begin
 update stu_e set stu_id = i.stu_id
 from stu_e e,deleted d,inserted i
 where e.stu_id = d.stu_id
 end
 begin
 update stu_cj set stu_id = i.stu_id
 from stu_e c,deleted d,inserted i
 where c.stu_id = d.stu_id
 end
commit transaction
---
update stu_info set stu_id =2 from stu_info where stu_id=4
select * from stu_info
select * from stu_e
select * from stu_cj

---------------------------------------------------------------------------
--觸發器delete

if exists(select * from sysobjects where name='T_test3')
begin
 drop Trigger T_test3
end
go
 create Trigger T_test3 on stu_info
for delete
as

declare  @stu_id int,
  @stu_nam char
select
 @stu_id =stu_id,
 @stu_nam =stu_nam
from deleted
begin transaction
if exists(select * from stu_e where stu_id=@stu_id)
begin
  Delete stu_e
         From stu_e e , deleted d
         Where e.stu_id=d.stu_id
end
if exists(select * from stu_cj where stu_id=@stu_id)
begin
  Delete stu_cj
         From stu_cj c , deleted d
         Where c.stu_id=d.stu_id
end
commit transaction

delete stu_info where stu_id=2

select * from stu_info
select * from stu_e
select * from stu_cj

聯繫我們

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