I'm trying to conditionally add a column and then update it in a single block:
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE [name] = N'outOf'
AND [object_id] = object_id(N'woRoute')
) BEGIN
ALTER TABLE woRoute
ADD outOf int NULL;
UPDATE woRoute set outOf = sampling
WHERE sampling is not null and sampling <> 0;
UPDATE woRoute set sampling = 1
WHERE outOf is not null;
END
but I get an error that "outOf" isn't a valid column, referencing the first UPDATE query.
I'm running this from Microsoft SQL Server Management Studio. If I run each piece separately, it all works fine. But if I try to run them together, I get that error.
How can I add this column, copy the value from another column in the table to it, and then update the other column's value, all under the condition that the new column doesn't exist yet?