views:

124

answers:

2

How would one write a sql server DDL script that can:

For each table in database:

add column CreatedBy
add column CreateDate
add column UpdatedBy
add column UpdatedDate

Also, if the particular column already exists on the table, just skip that column.

Also, the reverse of it, for each table, drop those 4 columns.

+2  A: 
DECLARE @TableName NVARCHAR(128)

DECLARE curTables CURSOR FAST_FORWARD FOR
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

OPEN curTables

FETCH NEXT FROM curTables INTO @TableName

WHILE (@@FETCH_STATUS = 0)
    BEGIN
        IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@TableName AND COLUMN_NAME='CreatedBy')
            EXECUTE ('ALTER TABLE [' + @TableName + '] ADD CreatedBy VARCHAR(50)')

        IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@TableName AND COLUMN_NAME='CreatedDate')
            EXECUTE ('ALTER TABLE [' + @TableName + '] ADD CreatedDate DATETIME')

        IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@TableName AND COLUMN_NAME='UpdatedBy')
            EXECUTE ('ALTER TABLE [' + @TableName + '] ADD UpdatedBy VARCHAR(50)')

        IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@TableName AND COLUMN_NAME='UpdatedDate')
            EXECUTE ('ALTER TABLE [' + @TableName + '] ADD UpdatedDate DATETIME')


        FETCH NEXT FROM curTables INTO @TableName   
    END

CLOSE curTables
DEALLOCATE curTables

Then the opposite is just a case of changing IF NOT EXISTS to IF EXISTS and the ALTER statements to ALTER TABLE...DROP [ColumnName]

AdaTheDev
Brilliant! Thanks a bunch.....
tbone