登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

梦想之鹰的天空

天高任鸟飞......放飞....心情..........放飞.....梦想

 
 
 

日志

 
 

触发器实现同时变更两张表  

2011-04-07 22:20:12|  分类: 数据库 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

--建立环境

create table table1 (sno varchar(10),sname varchar(10))
create table table2 (sno varchar(10),sname varchar(10))

go

create trigger t_table1 on table1
after delete,insert,update
as
begin
    delete from table2 where sno in (select sno from deleted)

    if not exists (select 1 from table2 a,inserted i where a.sno=i.sno)
        insert into table2
        select * from inserted
    else
        update a set a.sname=i.sname from table2 a,inserted i where a.sno=i.sno
end

go


/**********插入记录************/

insert into table1
select '0001','aa' union all
select '0002','bb' union all
select '0004','dd' 

select * from table1
select * from table2


--table1
/* 
sno     sname
-----  -------
0001    aa
0002    bb
0004    dd


--table2
sno      sname
------  -------
0001    aa
0002    bb
0004    dd
*/


/********删除记录*************/
delete from table1 where sno='0004'

select * from table1
select * from table2

--table1
/* 
sno     sname
-----  -------
0001    aa
0002    bb

--table2
sno      sname
------  -------
0001    aa
0002    bb
*/

 

/***********更新记录************/
update table1 set sname='cc' where sno='0002'

select * from table1
select * from table2

--table1
/* 
sno     sname
-----  -------
0001    aa
0002    cc

--table2
sno      sname
------  -------
0001    aa
0002    cc
*/


/********删除测试**********/

drop table table1,table2

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/bqb/archive/2008/01/28/2069578.aspx

  评论这张
 
阅读(525)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018