Search code examples
sql-serveralter-table

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


In one SQL script (SQL Server 2016) I want to add a column by using ALTER TABLE and change the values by using 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

but I get an error

Invalid column name 'MyAttribute'

for line 5 (the update statement).

The background for the code is:

  • The script is running every time a new program version for the database is installed (I can't change this behaviour)
  • MyAttribute should only be added at the first time of script execution
  • The value for all existing records should be 1, but the default value for all new records must be 0

Solution

  • They need to run in different batches:

    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
    

    EDIT:

    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