How do you add a NOT NULL Column to a large table in SQL Server?

前端 未结 12 1858
情话喂你
情话喂你 2020-12-02 15:42

To add a NOT NULL Column to a table with many records, a DEFAULT constraint needs to be applied. This constraint causes the entire ALTER TABLE command to take a long time to

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 16:02

    I had a similar problem and I went with modified #3 approach. In my case the database was in SIMPLE recovery mode and the table to which column was supposed to be added was not referenced by any FK constraints.

    Instead of creating a new table with the same schema and copying contents of original table, I used SELECT…INTO syntax.

    According to Microsoft (http://technet.microsoft.com/en-us/library/ms188029(v=sql.105).aspx)

    The amount of logging for SELECT...INTO depends on the recovery model in effect for the database. Under the simple recovery model or bulk-logged recovery model, bulk operations are minimally logged. With minimal logging, using the SELECT… INTO statement can be more efficient than creating a table and then populating the table with an INSERT statement. For more information, see Operations That Can Be Minimally Logged.

    The sequence of steps :

    1.Move data from old table to new while adding new column with default

     SELECT  table.*,   cast (‘default’ as nvarchar(256)) new_column
     INTO    table_copy 
     FROM    table
    

    2.Drop old table

     DROP TABLE  table
    

    3.Rename newly created table

     EXEC sp_rename 'table_copy',  ‘table’
    

    4.Create necessary constraints and indexes on the new table

    In my case the table had more than 100 million rows and this approach completed faster than approach #2 and log space growth was minimal.

提交回复
热议问题