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

后端 未结 30 2773
轮回少年
轮回少年 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条回答
  •  猫巷女王i
    2020-11-22 12:03

    This can be done by the below code.

    CREATE TABLE TestTable
        (FirstCol INT NOT NULL)
        GO
        ------------------------------
        -- Option 1
        ------------------------------
        -- Adding New Column
        ALTER TABLE TestTable
        ADD SecondCol INT
        GO
        -- Updating it with Default
        UPDATE TestTable
        SET SecondCol = 0
        GO
        -- Alter
        ALTER TABLE TestTable
        ALTER COLUMN SecondCol INT NOT NULL
        GO
    

提交回复
热议问题