Dynamic Trigger creation

  • 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

  • You'll have to add the primary key to a Where clause in the trigger.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply