I must add a Not Nullable column, but I don't have a known value for default so I create the column as Nullable, after that I update all rows and then change the column to be Not Nullable.
Running the following script finished with success.
BEGIN
ALTER TABLE driver ADD DriverLocationId INT NULL
EXEC('UPDATE driver
SET DriverLocationId = (SELECT TOP(1) CountryId FROM Country WHERE CountryCode IN (''USA'',''CAN'', ''MEX''))')
ALTER TABLE driver ALTER COLUMN DriverLocationId INT NOT NULL
END
And the following is failing.
BEGIN
ALTER TABLE driver ADD DriverLocationId INT NULL
UPDATE driver
SET DriverLocationId = (SELECT TOP(1) CountryId FROM Country WHERE CountryCode IN ('USA','CAN', 'MEX'))
ALTER TABLE driver ALTER COLUMN DriverLocationId INT NOT NULL
END
Probably when the update script from 1st attempt is executed correctly after altering.
Do you have any explanation for this?
EDIT: I have updated my question. Sorry for the double quotes. That wasn't a problem. Here is something more complicated.
EDIT: The error is:
Invalid column name 'DriverLocationId'.
EDIT (for @Stephan): GO isn't working there