SQL Server 2017 添加新列,默认值来自同一 table 中的另一列

SQL Server 2017 add new column with default value from another column in the same table

我有一个简单的列 Weight1,它的类型是 floatnot null。我想添加一个新列 Weight2,默认值来自 Weight1,因此 Weight1Weight2 将相同。

任何人都可以帮助如何做到这一点?

我尝试了以下方法:

IF EXISTS
(
    SELECT 1
    FROM sys.tables
    WHERE Object_ID = OBJECT_ID(N'[dbo].[TableA]')
) AND NOT EXISTS
(
    SELECT 1
    FROM sys.columns
    WHERE Name = N'Weight2' AND
          Object_ID = OBJECT_ID(N'[dbo].[TableA]')
)
BEGIN
    PRINT 'Adding Weight2 to [dbo].[TableA]';   

    ALTER TABLE [dbo].[TableA] 
        ADD [Weight2] FLOAT NOT NULL 
END

我得到的错误是:

ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column.

Column 'Weight2' cannot be added to non-empty table 'TableA' because it does not satisfy these conditions.

谢谢

您可以添加该列并使其成为从 Weight1 获取值的计算列:

ALTER TABLE [TableA] ADD [Weight2] AS ([Weight1])  PERSISTED

希望对您有所帮助。

该错误清楚地告诉您:如果您将带有 NOT NULL 的列添加到已包含数据的 table 中,则您 必须 包含一个DEFAULT 子句为新添加的列定义默认值 - 你没有这样做....

所以试试这个:

ALTER TABLE [dbo].[TableA] 
    ADD [Weight2] FLOAT NOT NULL
    CONSTRAINT DF_TableA_Weight2 DEFAULT(0);

然后您可以更新 Weight2 以获得与 Weight1 中相同的值:

UPDATE dbo.TableA
SET Weight2 = Weight1