日期:2014-05-19  浏览次数:20448 次

求救:触发器的问题(立即结贴)
有表A,B,C如下:

表A
aid int
aname nvarchar(30) 用户名
dtime datetime 登录时间
atimes int 登录次数

表B
bid int
bname nvarchar(30)
dtime datetime

表C
cid int
cname nvarchar(30)
dtime datetime


在A表上插入数据时,自动向表C插入数据,已有触发器如下:
Create   Trigger   tr_t   on   A   for   insert
AS
declare   @aname   nvarchar(30)
select   @aname   =   aname   from   inserted
insert   into   C(cname)   values(@aname)

问在A表的列atimes和dtime发生更新时(我所说的更新是指update表A的atime和dtime列时,不包含insert)自动更新表B的触发器该怎么写?

------解决方案--------------------
Create Trigger tr_t on A for update
AS
if update (atimes,dtime)
begin
想更新的内容
end
------解决方案--------------------
需要写两个 因为一个触发器 for insert 和 update 完全两种触发器 不可一连用
------解决方案--------------------
-----create test environment---

create table A
(aid int, aname nvarchar(30), dtime datetime, atimes int)

create table B
(bid int, bname nvarchar(30), dtime datetime)

create table C
(cid int, cname nvarchar(30), dtime datetime)

---------SQL-------
--the first trigger on table A

if exists (select [name] from sysobjects where [name] = 'tr_t ')
drop trigger tr_t
go

Create Trigger tr_t on A
for insert
AS
declare @aname nvarchar(30)
select @aname = aname from inserted
insert into C(cname) values(@aname)

go

-----the second trigger on table A
if exists (select [name] from sysobjects where [name] = 'tr_t2 ')
drop trigger tr_t2
go

create trigger tr_t2 on A
for update
as
declare @aname2 nvarchar(30)
if (((select count(*) from inserted) > 0) and ((select count(*) from deleted) > 0))
select @aname2 = aname from inserted
update C set cname = @aname2

go
------Check data--

insert into A(aname) values( 'Mike ')
go
select * from C
go
update A set aname = 'Kite '
go

select * from C
go

----------delete test environment-------
drop table A,B,C

----------Result---

(1 件処理されました)

cid cname dtime
----------- ---- --------
NULL Mike NULL

(1 件処理されました)


(1 件処理されました)

cid cname dtime
----------- --------------------
NULL Kite NULL

(1 件処理されました)