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

前端 未结 12 1896
情话喂你
情话喂你 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 would use CURSOR instead of UPDATE. Cursor will update all matching records in batch, record by record -- it takes time but not locks table.

    If you want to avoid locks use WAIT.

    Also I am not sure, that DEFAULT constrain changes existing rows. Probably NOT NULL constrain use together with DEFAULT causes case described by author.

    If it changes add it in the end So pseudocode will look like:

    -- without NOT NULL constrain -- we will add it in the end
    ALTER TABLE table ADD new_column INT DEFAULT 0
    
    DECLARE fillNullColumn CURSOR LOCAL FAST_FORWARD
        SELECT 
            key
        FROM
            table WITH (NOLOCK)
        WHERE
            new_column IS NULL
    
    OPEN fillNullColumn
    
    DECLARE 
        @key INT
    
    FETCH NEXT FROM fillNullColumn INTO @key
    
    WHILE @@FETCH_STATUS = 0 BEGIN
         UPDATE
             table WITH (ROWLOCK)
         SET
             new_column = 0 -- default value
         WHERE
             key = @key
    
         WAIT 00:00:05 --wait 5 seconds, keep in mind it causes updating only 12 rows per minute
    
         FETCH NEXT FROM fillNullColumn INTO @key
    END
    
    CLOSE fillNullColumn
    DEALLOCATE fillNullColumn
    
    ALTER TABLE table ALTER COLUMN new_column ADD CONSTRAIN xxx
    

    I am sure that there are some syntax errors, but I hope that this help to solve your problem.

    Good luck!

提交回复
热议问题