Requirement: Modify the value of a field in the main table and automatically update a field in the child table
In order not to change the program, we create an update trigger.
create trigger [tig_update] on 表名
after update
as
declare @id int
begin
if (update(main table column name))
begin
select @id=id from inserted
update 子表名 set lasttime = GETDATE() where pid = @id
end
end
The effect does not seem to be right, and ifupdate(a) is used alone, it does not reflect the effect, why?
if we execute
update main table set column name a = original value where id = id
The discovery also triggers this event, which is wrong. Only when the value of the column name a changes, can we modify the data of the sub-table:
We changed to the following trigger, and the effect came out
create trigger [tig_update] on 表名
after update
as
declare @id int,
@upflag int
begin
select @upflag = case when a.列名=b.列名 then 0 else 1 end, @id=a.id from deleted a left join inserted b on a.id = b.id
if (@upflag>0)
update 子表名 set lasttime = GETDATE() where pid = @id
end
Explain, the deleted table stores the value before modification, and the inserted value stores the modified value. Isn't this better!