В зависимости от других событий, происходящих с этими данными, триггеры могут быть очень неэффективным методом обработки этого, но вот одно из возможных решений.
1. Настройка
Сначала создайте таблицу для тестирования.
create table test_table (
MyPrimaryKey int primary key clustered not null identity(1, 1)
, SomeColumn varchar(255) not null
, SomeColumnCounter int null
);
go
Теперь добавьте триггер для инициализации счетчика в 1. Это может быть обработано ограничением по умолчанию или установлено на уровне приложения, но это также может быть сделано с помощью триггера.
-- this trigger will set the counter to 1 when a record is first added
-- doesn't need to be a trigger, but since the question was on triggers
create trigger trg_test_table_insert
on test_table
after insert
as
update tt
set tt.SomeColumnCounter = 1
from
test_table as tt
inner join
Inserted as i
on
tt.MyPrimaryKey = i.MyPrimaryKey;
go
Теперь добавьте триггер, который будет проверять изменения в указанном столбце, и при необходимости увеличьте счетчик.
-- this trigger will increment the counter by 1 if 'SomeColumn' changed
-- doesn't handle nulls so will need to be modified depending on schema
create trigger trg_test_table_update
on test_table
after update
as
update tt
set tt.SomeColumnCounter = tt.SomeColumnCounter + 1
from
Inserted as i -- new version of the record
inner join
Deleted as d -- old version of the record
on
i.MyPrimaryKey = d.MyPrimaryKey
and i.SomeColumn <> d.SomeColumn
inner join
test_table as tt
on
tt.MyPrimaryKey = i.MyPrimaryKey
go
2. Тестирование
Добавить некоторые данные испытаний.
insert into test_table (SomeColumn)
values ('abc'), ('def');
go
Теперь у нас есть:
MyPrimaryKey SomeColumn SomeColumnCounter
1 abc 1
2 def 1
Обновление без изменений:
update tt
set tt.SomeColumn = 'abc'
from
test_table as tt
where
tt.MyPrimaryKey = 1
У нас еще есть:
MyPrimaryKey SomeColumn SomeColumnCounter
1 abc 1
2 def 1
Обновление, которое на самом деле что-то меняет:
update tt
set tt.SomeColumn = 'abbc'
from
test_table as tt
where
tt.MyPrimaryKey = 1
Теперь у нас есть:
MyPrimaryKey SomeColumn SomeColumnCounter
1 abbc 2
2 def 1
Обновление, которое меняет все:
update tt
set tt.SomeColumn = tt.SomeColumn + 'z'
from
test_table as tt
Теперь у нас есть:
MyPrimaryKey SomeColumn SomeColumnCounter
1 abbcz 3
2 defz 2