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

前端 未结 12 1886
情话喂你
情话喂你 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 15:47

    Here's what I would try:

    • Do a full backup of the database.
    • Add the new column, allowing nulls - don't set a default.
    • Set SIMPLE recovery, which truncates the tran log as soon as each batch is committed.
    • The SQL is: ALTER DATABASE XXX SET RECOVERY SIMPLE
    • Run the update in batches as you discussed above, committing after each one.
    • Reset the new column to no longer allow nulls.
    • Go back to the normal FULL recovery.
    • The SQL is: ALTER DATABASE XXX SET RECOVERY FULL
    • Backup the database again.

    The use of the SIMPLE recovery model doesn't stop logging, but it significantly reduces its impact. This is because the server discards the recovery information after every commit.

提交回复
热议问题