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

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

    Maybe like this:

    EXEC sp_MSforeachtable '
        declare @tblname varchar(255);
        SET @tblname =  PARSENAME("?",1);
    
        if not exists (select column_name from INFORMATION_SCHEMA.columns 
                       where table_name = @tblname and column_name = ''CreatedOn'') 
        begin
            ALTER TABLE [?] ADD CreatedOn datetime NOT NULL DEFAULT getdate();
        end
    '
    

    ?

    Or even like this:

    EXEC sp_MSforeachtable '
        if not exists (select column_name from INFORMATION_SCHEMA.columns 
                       where table_name = ''?'' and column_name = ''CreatedOn'') 
        begin
            ALTER TABLE [?] ADD CreatedOn datetime NOT NULL DEFAULT getdate();
        end
    '
    

提交回复
热议问题