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:
MyAttribute
should only be added at the first time of script executionThey 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