Creating a trigger dynamically for all my tables

Last post 09-08-2008, 11:33 AM by randyvol. 1 replies.
Sort Posts: Previous Next
  •  07-24-2008, 6:52 AM Post number 63916

    Creating a trigger dynamically for all my tables

    Good day ALL

    Below is a script I created to add auditing to all my tables. (More than 100)
    The only problem is that the trigger that I create updates ALL the rows in the table.

    Is there a way that the trigger can only update the “Updated” record without specifying a particular field in the table?

    Declare @TableName nvarchar(100)
    Declare @SQL nvarchar(1000)

    declare tables_cursor CURSOR FOR
                select [name] from sysobjects
                where xtype = 'U'
                and [name] not like 'sys%'
                order by [name]
    Open tables_cursor

    fetch next from tables_cursor into @TableName
    WHILE @@FETCH_STATUS = 0
    Begin
    --Add audit table
                set @SQL = 'ALTER TABLE '+@TableName+' ADD audDateLastChanged datetime DEFAULT getdate()'
                exec (@SQL)
                print @SQL

    --update current records
                set @SQL = 'update '+@TableName+' set audDateLastChanged = getdate()'
                exec (@SQL)
                print @SQL

    --create trigger for updates on each table
                set @SQL = 'create trigger trg_u_'+@TableName+'_audDatelastChanged '
                set @SQL = @SQL + ' on '+@TableName
                set @SQL = @SQL + ' for update '
                set @SQL = @SQL + ' as '
                set @SQL = @SQL + ' begin '
                set @SQL = @SQL + '    update '+@TableName
                set @SQL = @SQL + '      set audDateLastChanged = getdate()'
                set @SQL = @SQL + '      from inserted'
                set @SQL = @SQL + ' end'
                exec (@SQL)
                print @SQL

                fetch next from tables_cursor into @TableName
    end

    CLOSE tables_cursor
    DEALLOCATE tables_cursor
  •  09-08-2008, 11:33 AM Post number 69454 in reply to post number 63916

    • randyvol is not online. Last active: 11-12-2008, 4:06 PM randyvol
    • Top 25 Contributor
    • Joined on 04-04-2007
    • Columbia, SC (USA)
    • Level 2: Deep Blue

    Re: Creating a trigger dynamically for all my tables

    FROM BOL:
    You can design a Transact-SQL trigger to perform certain actions based on UPDATE or INSERT modifications to specific columns. Use UPDATE() or COLUMNS_UPDATED in the body of the trigger for this purpose.
    UPDATE() tests for UPDATE or INSERT tries on one column. COLUMNS_UPDATED tests for UPDATE or INSERT actions that are performed on multiple columns and returns a bit pattern that indicates which columns were inserted or updated.

    snipplet follows:

    CREATE TRIGGER [dbo].[upd_armaster_pmttermsdesc] ON [Whaley].[dbo].[armaster_all] AFTER UPDATE

    AS

    IF UPDATE(terms_code) -- test for update on column, 'terms_code'

View as RSS news feed in XML