Add a column if it doesn't exist to all tables?

前端 未结 4 1250
忘了有多久
忘了有多久 2021-02-05 01:30

I\'m using SQL Server 2005/2008. I need to add a column to a table if it does not yet exist. This will apply to all tables in a given database. I hoped I was close, but I\'m h

4条回答
  •  孤独总比滥情好
    2021-02-05 02:26

    DECLARE @Column VARCHAR(100) = 'Inserted_date'
    DECLARE @sql VARCHAR(max) = NULL
    
    SELECT @sql += ' ALTER TABLE ' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) + 'ADD' + @Column + 'datetime NOT NULL DEFAULT getdate()' + '; '
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_TYPE = 'BASE TABLE'
        AND TABLE_NAME IN (
            SELECT DISTINCT NAME
            FROM SYS.TABLES
            WHERE type = 'U'
                AND Object_id IN (
                    SELECT DISTINCT Object_id
                    FROM SYS.COLUMNS
                    WHERE NAME != @Column
                    )
            )
    EXEC Sp_executesql @sql
    

提交回复
热议问题