开发者

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

开发者 https://www.devze.com 2023-01-17 15:07 出处:网络
I have many tables that have a [DateCreated] column that also needs a [DateModified] column. The [DateModified] column will need an Update tr开发者_JAVA技巧igger that inserts the current date (getdat

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

The [DateModified] column will need an Update tr开发者_JAVA技巧igger that inserts the current date (getdate()) into this new [DateModified] column.

Each table uses custom schema, not [dbo].

Whats the easiest/best way to do this?


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

精彩评论

暂无评论...
验证码 换一张
取 消