添加新列并更改同一 SQL 脚本中的值时出错

Error when adding a new column and change the value in the same SQL script

在一个 SQL 脚本(SQL Server 2016)中,我想使用 ALTER TABLE 添加一列并使用 UPDATE 更改值:

IF NOT EXISTS (SELECT * FROM sys.all_columns  
               WHERE object_id = OBJECT_ID(N'MyTable') and NAME = 'MyAttribute')
BEGIN
    ALTER TABLE MyTable 
        ADD MyAttribute BIT NOT NULL DEFAULT(0);

    UPDATE MyTable 
    SET MyAttribute = 1;
END

但是我得到一个错误

Invalid column name 'MyAttribute'

第 5 行(update 语句)。

代码的背景是:

他们需要分批运行:

declare @new bit = 0;

IF NOT EXISTS (SELECT * FROM sys.all_columns  
               WHERE object_id = OBJECT_ID(N'MyTable') and NAME = 'MyAttribute')
BEGIN
    set @new = 1;
    ALTER TABLE MyTable ADD MyAttribute BIT NOT NULL DEFAULT(0);

END
Go
if @new = 1
begin
    UPDATE MyTable SET MyAttribute = 1;
end

编辑:

IF NOT EXISTS (SELECT * FROM sys.all_columns  
               WHERE object_id = OBJECT_ID(N'MyTable') and NAME = 'MyAttribute')
BEGIN
    ALTER TABLE MyTable 
        ADD MyAttribute BIT NOT NULL 
        CONSTRAINT df_attr DEFAULT(1);
    ALTER TABLE MyTable
        DROP CONSTRAINT df_attr; 
    ALTER TABLE MyTable
        ADD CONSTRAINT df_attr DEFAULT 0 FOR MyAttribute; 
END