日期:2014-05-18  浏览次数:20584 次

关于触发器的一个简单问题。
我想问一下,我现在数据库有两个表,例如是A   B两个。
我现在想修改A表里面的name字段里面一条记录内容,让B表的name记录内容跟A表的记录相同的记录也被修改。

各位高手给个例子那。谢谢了

------解决方案--------------------
假设两表都是以id为主键,而且关联

create trigger tr_a_update
on a
for update
as
if update (name)
update b
set name=i.name
from inserted i
where i.id=b.id

go

------解决方案--------------------
假如A表和B表通过name相关联!
Create trigger roy on a
for update
as
begin
if update(name)
update b set b.name=i.name from b,inserted i,deleted d
where b.name=d.name
end
------解决方案--------------------
Create Table a (name varchar(10))
insert into a select 'aaa '
insert into a select 'bbb '
insert into a select 'ccc '


Create Table b (name varchar(10))
insert into b select 'aaa '
insert into b select 'bbb '
insert into b select 'ccc '

Create trigger roy on a
for update
as
begin
if update(name)
update b set b.name=i.name from b,inserted i,deleted d
where b.name=d.name
end

update a set name= 'ddd '
where name= 'aaa '

select * from a
select * from b



------解决方案--------------------
create trigger test on a
for update
as
if update(name)
update b set name=inserted.name from inserted on b.name=inserted.name
------解决方案--------------------
create table t_a(id int identity(1,1) primary key,name varchar(20) null)

create table t_b(id int null ,name varchar(20) null)
go
create trigger ut_t_a on t_a
for update
as
begin
if exists(select * from inserted as i join t_b as b on i.id=b.id )
begin
update t_b set name= inserted.name from inserted where inserted.id=t_b.id
end
end


insert into t_a(name) values( 'ivan ')

insert into t_a(name) values( 'join ')

insert into t_a(name) values( 'dure ')

insert into t_a(name) values( 'joson ')


insert into t_b(id,name) values(1, 'ivan ')

insert into t_b(id,name) values(2, 'join ')

insert into t_b(id,name) values(3, 'dure ')

insert into t_b(id,name) values(4, 'joson ')


select * from t_a
select * from t_b

update t_a set name= 'ddddd '
where id=1 and name= 'ivan '

drop table t_a
drop table t_b