如何将具有默认值的列添加到SQL Server 2000/SQL Server 2005中的现有表中?


当前回答

SQL Server+更改表+添加列+默认值uniqueidentifier

ALTER TABLE Product 
ADD ReferenceID uniqueidentifier not null 
default (cast(cast(0 as binary) as uniqueidentifier))

其他回答

当要添加的列具有NOT NULL约束,但没有DEFAULT约束(值)时,请注意。在这种情况下,如果表中有任何行,ALTER TABLE语句将失败。解决方案是从新列中删除NOT NULL约束,或为其提供DEFAULT约束。

这可以通过以下代码完成。

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
ALTER TABLE Table1 ADD Col3 INT NOT NULL DEFAULT(0)
ALTER TABLE Protocols
ADD ProtocolTypeID int NOT NULL DEFAULT(1)
GO

DEFAULT的包含使用默认值填充现有行中的列,因此不违反NOT NULL约束。

试试这个

ALTER TABLE Product
ADD ProductID INT NOT NULL DEFAULT(1)
GO