Как я могу обновить столбец в SQL Server с помощью триггера - PullRequest
0 голосов
/ 01 апреля 2019

Я пытаюсь создать в SQL Server Management Studio триггер, который будет увеличивать значение столбца на 1 при обновлении отдельного столбца в той же таблице.

Значение для столбца, который мы хотим обновить при запуске сценария обновления, становится NULL

Мой пример: когда я меняю адрес клиента, я хочу, чтобы столбец увеличивался на 1 при каждом изменении адреса, т.е. NoOfAddressess = 1, 2, 3 и т. Д. *

Вот код SQL, который я пишу

ALTER TRIGGER trg_customeraudit 
ON tblCustomer
AFTER UPDATE, DELETE, INSERT
AS
    INSERT INTO dbo.CustomerDetailsAudit 
    VALUES (CURRENT_USER, CURRENT_TIMESTAMP, 
            (SELECT CustomerID FROM inserted), 
            (SELECT CustomerAddress FROM deleted), 
            (SELECT CustomerAddress FROM inserted),
            (SELECT CustomerPostcode FROM deleted), 
            (SELECT CustomerPostcode FROM inserted), 
            (SELECT NumberOfChangedAddresses FROM dbo.CustomerDetailsAudit)  
           )

    IF ((SELECT CustomerAddress FROM inserted) = 
        (SELECT CustomerAddress FROM deleted) OR 
        (SELECT CustomerPostcode FROM deleted) = 
        (SELECT CustomerPostcode FROM inserted))
    BEGIN
        RAISERROR ('You must enter both a new postcode and address',16,10)
        ROLLBACK TRANSACTION
    END 
ELSE
BEGIN 
    PRINT 'Transaction successful'
    WHERE CustomerID = (SELECT CustomerID from inserted)
END

IF UPDATE (CustomerName)
BEGIN
    RAISERROR ('You cannot change the customer name', 16, 10)
    ROLLBACK
END

1 Ответ

0 голосов
/ 02 апреля 2019

В зависимости от других событий, происходящих с этими данными, триггеры могут быть очень неэффективным методом обработки этого, но вот одно из возможных решений.

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...