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

前端 未结 12 1860
情话喂你
情话喂你 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:01

    I ran into this problem for my work also. And my solution is along #2.

    Here are my steps (I am using SQL Server 2005):

    1) Add the column to the table with a default value:

    ALTER TABLE MyTable ADD MyColumn varchar(40) DEFAULT('')
    

    2) Add a NOT NULL constraint with the NOCHECK option. The NOCHECK does not enforce on existing values:

    ALTER TABLE MyTable WITH NOCHECK
    ADD CONSTRAINT MyColumn_NOTNULL CHECK (MyColumn IS NOT NULL)
    

    3) Update the values incrementally in table:

    GO
    UPDATE TOP(3000) MyTable SET MyColumn = '' WHERE MyColumn IS NULL
    GO 1000
    
    • The update statement will only update maximum 3000 records. This allow to save a chunk of data at the time. I have to use "MyColumn IS NULL" because my table does not have a sequence primary key.

    • GO 1000 will execute the previous statement 1000 times. This will update 3 million records, if you need more just increase this number. It will continue to execute until SQL Server returns 0 records for the UPDATE statement.

提交回复
热议问题