Add “DateModified” Column with an Update Trigger To All Tables that contain a “DateCreated” Column

后端 未结 1 1122
情话喂你
情话喂你 2021-01-15 13:41

I have many tables that have a [DateCreated] column that also needs a [DateModified] column.

The [DateModified] column will ne

相关标签:
1条回答
  • 2021-01-15 14:32

    This will get you the alter table statements, which you can cut/paste into a new query window to execute. I'll leave it as an exercise for the reader to use this same technique to generate the create trigger statements.

    select 'alter table ' + quotename(s.name) + '.' + quotename(t.name) + ' add [DateModified] datetime'
        from sys.columns c
            inner join sys.tables t
                on c.object_id = t.object_id
            inner join sys.schemas s
                on t.schema_id = s.schema_id
            left join sys.columns c2
                on t.object_id = c2.object_id
                    and c2.name = 'DateModified'
        where c.name = 'DateCreated'
            and t.type = 'U'
            and c2.column_id is null /* DateModified column does not already exist */
    
    0 讨论(0)
提交回复
热议问题