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

前端 未结 4 1249
忘了有多久
忘了有多久 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:33

    You cannot use variables, like @tableName, in DDL. Besides, splinting the name into part and ignoring the schema can only result in bugs. You should just use the ''?'' replacement in the SQL batch parameter and rely on the MSforeachtable replacement:

    EXEC sp_MSforeachtable '
    if not exists (select * from sys.columns 
                   where object_id = object_id(''?'')
                   and name = ''CreatedOn'') 
    begin
        ALTER TABLE ? ADD CreatedOn datetime NOT NULL DEFAULT getdate();
    end';
    

提交回复
热议问题