Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Criar gatilho para inserir um valor de coluna em outra coluna da mesma tabela SQL Server 2005


Experimente este gatilho (ele irá copiar os valores da ColunaB para a ColunaA quando forem inseridos valores na ColunaB ou quando forem atualizados os valores da ColunaB):
CREATE TRIGGER trgIU_triggertestTable_UpdateColumnAWhenColumnB
   ON  dbo.triggertestTable
   AFTER INSERT,UPDATE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    IF UPDATE(ColumnB)
    BEGIN
        UPDATE  dbo.triggertestTable
        SET     ColumnA=i.ColumnB
        FROM    inserted i
        INNER JOIN dbo.triggertestTable t ON i.MyID=t.MyID
        LEFT JOIN deleted d ON i.MyID=d.MyID
        WHERE   d.MyID IS NULL AND i.ColumnB IS NOT NULL -- Row was inserted
        OR      d.MyID IS NOT NULL -- Row was updated
    END
END
GO

Usei esta tabela:
CREATE TABLE dbo.triggertestTable(
    MyID INT IDENTITY(1,1) PRIMARY KEY, -- MyID should be a PRIMARY KEY or a mandatory(NOT NULL) UNIQUE constraint
    ColumnA VARCHAR(100),
    ColumnB VARCHAR(100)
);
GO