这个监视字段变化的触发器该怎么写?
我想监视表table1
某行记录被UPDATE,
当A字段原先不为空时,若A字段发生变化或B字段发生变化,则将C字段设为NULL
当A字段原先为空时,若D字段发生变化或B字段发生变化,则将C字段设为NULL
这个触发器该怎么写啊?
[解决办法]
create trigger dbo.trigger_table1_update
on dbo.table1
as
if exists(select a from deleted where a is not null) and
(update(a) or UPDATE(b))
begin
update table1
set c = null
from inserted i
where table1.id = i.id
end
if exists(select a from deleted where a is null) and
(update(d) or UPDATE(b))
begin
update table1
set c = null
from inserted i
where table1.id = i.id
end
go
create trigger tr_table1
on table1 for update
as
begin
update a
set a.C字段=null
from table1 a
where exists
(select 1
from deleted b
inner join inserted c on b.id=c.id
where b.id=a.id and b.A字段 is not null and (b.A字段<>c.A字段 or b.B字段<>c.B字段))
or exists
(select 1
from deleted b
inner join inserted c on b.id=c.id
where b.id=a.id and b.A字段 is null and (b.D字段<>c.D字段 or b.B字段<>c.B字段))
end