Add a column with a default value to an existing table in SQL Server

后端 未结 30 2838
轮回少年
轮回少年 2020-11-22 12:00

How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?

30条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 12:15

    This has a lot of answers, but I feel the need to add this extended method. This seems a lot longer, but it is extremely useful if you're adding a NOT NULL field to a table with millions of rows in an active database.

    ALTER TABLE {schemaName}.{tableName}
        ADD {columnName} {datatype} NULL
        CONSTRAINT {constraintName} DEFAULT {DefaultValue}
    
    UPDATE {schemaName}.{tableName}
        SET {columnName} = {DefaultValue}
        WHERE {columName} IS NULL
    
    ALTER TABLE {schemaName}.{tableName}
        ALTER COLUMN {columnName} {datatype} NOT NULL
    

    What this will do is add the column as a nullable field and with the default value, update all fields to the default value (or you can assign more meaningful values), and finally it will change the column to be NOT NULL.

    The reason for this is if you update a large scale table and add a new not null field it has to write to every single row and hereby will lock out the entire table as it adds the column and then writes all the values.

    This method will add the nullable column which operates a lot faster by itself, then fills the data before setting the not null status.

    I've found that doing the entire thing in one statement will lock out one of our more active tables for 4-8 minutes and quite often I have killed the process. This method each part usually takes only a few seconds and causes minimal locking.

    Additionally, if you have a table in the area of billions of rows it may be worth batching the update like so:

    WHILE 1=1
    BEGIN
        UPDATE TOP (1000000) {schemaName}.{tableName}
            SET {columnName} = {DefaultValue}
            WHERE {columName} IS NULL
    
        IF @@ROWCOUNT < 1000000
            BREAK;
    END
    

提交回复
热议问题