1

i'm trying to create a trigger for log any change in many tables. but now, i'm testing in just one table called "MAN_OS_TIPO".

The objective:

I need to detect which column has been changed and put the OLD and NEW values into the log table "SYS_LOG_UPDATE"

PS: If you know another way to LOG the updates, please let me know

The Log Table:

  • Name of table [Tabela]
  • Name of column [Coluna]
  • old value [DadoAntigo]
  • new value [DadoNovo]
  • app user [Usuario]
  • operation date [Data]

PS: This table will store log data from many tables.

The Table

This is the CODE used to create the table:

USE [SIGO]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
DROP TABLE dbo.MAN_OS_TIPO    -- Just for test faster

/* CREATE */
CREATE TABLE dbo.MAN_OS_TIPO (
    Id int IDENTITY(1,1) NOT NULL,
    Descricao nvarchar(30) NOT NULL,
    /* System */
    LData datetime NULL,
    LUser int NULL,
    CData datetime NOT NULL,
    CUser int NULL
CONSTRAINT [PK_MAN_OS_TIPO] PRIMARY KEY NONCLUSTERED (
    [Id] ASC
) WITH (
    PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY]
GO
/* DEFAULT */ ALTER TABLE dbo.MAN_OS_TIPO ADD CONSTRAINT DF_MAN_OS_TIPO_CDATA DEFAULT getdate() for [CData]
GO
/* UNIQUE */ ALTER TABLE dbo.MAN_OS_TIPO ADD CONSTRAINT UQ_MAN_OS_TIPO_DESCRICAO UNIQUE (Descricao)
GO

The Trigger

/* TRIGGER */
CREATE TRIGGER TR_MAN_OS_TIPO_UPDATE ON dbo.MAN_OS_TIPO
FOR UPDATE
AS
    DECLARE
        @OldValue nvarchar(max),    -- Valor antigo
        @NewValue nvarchar(max),    -- Valor novo
        @LUser int,                 -- Usuário que está alterando
        @Id int,            -- Id do registro


        @qtd int,               -- Quantity of column in table
        @cont int,              -- while Counter
        @tab nvarchar(max),     -- Name of table
        @col nvarchar(max),     -- Name of column
        @sql nvarchar(max),     -- SQL

    SET @cont = 1
    SET @tab = 'MAN_OS_TIPO'

    -- Count how many columns the table has
    SELECT @qtd = COUNT(*) FROM [INFORMATION_SCHEMA].[COLUMNS] WHERE TABLE_NAME = @tab


    WHILE (@cont <= @qtd)
    BEGIN
        SELECT @col = COLUMN_NAME FROM [INFORMATION_SCHEMA].[COLUMNS] WHERE     TABLE_NAME = @tab AND ORDINAL_POSITION = @cont

        IF (@col != 'Id' AND @col != 'CUser' AND @col != 'CData' AND @col !=    'LUser' AND @col != 'LData')
        BEGIN
            PRINT @col
            -- Get old values
            SELECT @Id = Id, @OldValue = CAST(convert(nvarchar,@col,103) AS     NVARCHAR) FROM DELETED

            -- Get new values
            SELECT @NewValue = CAST(convert(nvarchar,' + @col + ',103) AS NVARCHAR), @LUser = LUser FROM INSERTED

            PRINT 'old: ' + @OldValue + ' // new: ' + @NewValue    -- Just for debug
            IF (@NewValue != @OldValue)    -- Just if the value was changed
            BEGIN
                -- Insert in the log table
                INSERT INTO [dbo].[SYS_LOG_UPDATE] ([Tabela],[Coluna],  [DadoAntigo],[DadoNovo],[Usuario],[Data])
                    VALUES (@tab,@col,@OldValue,@NewValue,@LUser,getdate())
                PRINT 'LOG!'    -- Just for debug
            END
        END
        SET @cont = @cont + 1
    END
    SET @sql = 'UPDATE ' + @tab + ' SET [LData] = getdate() WHERE [Id] = ' +    CAST(@Id AS nvarchar)    -- Just inform the last update date
    PRINT @sql
    EXEC(@sql)
GO

This code is used to populate the table:

-- Insert new value
INSERT INTO [dbo].[MAN_OS_TIPO]
           ([Descricao]
           ,[CData]
           ,[CUser])
     VALUES
           ('Corretiva',
           getdate(),
           1)
GO

-- Update value
UPDATE [dbo].[MAN_OS_TIPO]
   SET [Descricao] = 'Corretiva A'
      ,[LUser] = 2
 WHERE [Descricao] = 'Corretiva'
GO

The Problem

When i try to get the old value...

SELECT @Id = Id, @OldValue = CAST(convert(nvarchar,@col,103) AS     NVARCHAR) FROM DELETED

...the @OldValue receive the name of the column. But i need to get the value inside the column.

I could specify manually all the names of columns, but this will leave very large code.

by the way... If you know how can i get the value of the column or register all updates in the log table, i'll so glad.

9
  • 1
    Your whole approach to this problem is wrong, These while loops (performance killers), selecting variables from deleted table (will fail in case of multiple row update) , I answered a question a couple of days ago with similar requirements , have a look here I am looking for a way for a trigger to insert into a second table only where the value in table 1 changes
    – M.Ali
    Feb 26, 2015 at 22:44
  • 1
    One other thing to consider is the design of your auditing table. What you have here is an EAV type of table. Consider how incredibly difficult it is going to be to accurately reflect what the values of RowX where at 8:34am on March 3rd 2012. If you need to audit changes then at some point management is going to ask for that exact scenario. Or even worse, they will want to see a full audit of all changes made since the beginning of time. In your design this is incredibly difficult.
    – Sean Lange
    Feb 26, 2015 at 23:17
  • 1
    Upgrade to SQL Server 2008 and use CDC. technet.microsoft.com/en-us/library/…
    – sam yi
    Feb 27, 2015 at 3:34
  • 1
    Or use the SCD concept to keep old records in there .. to be cleaned up at a later time. Specifically the "type 2" SCD. en.wikipedia.org/wiki/Slowly_changing_dimension
    – sam yi
    Feb 27, 2015 at 3:36
  • 1
    OK. I have done this type of auditing it is not as easy as it seems to recreate what the rows looked like over the course of time. Think about a table with just 10 columns and 40 updates each update changing various columns. Now from your structure what did the whole row look like at a given point in time.
    – Sean Lange
    Feb 27, 2015 at 14:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.