Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server DDL script to append (or drop) the same set of columns for every table in a database?

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.

like image 757
tbone Avatar asked Dec 21 '25 00:12

tbone


1 Answers

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]

like image 76
AdaTheDev Avatar answered Dec 22 '25 17:12

AdaTheDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!