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