In my TSQL script I have an IF THEN ELSE structure that checks if a column already exists.
If not it creates the column and updates it.
IF NOT EXISTS(
SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'tableName' AND COLUMN_NAME = 'columnName'))
BEGIN
BEGIN TRANSACTION
ALTER TABLE tableName
ADD columnName int NULL
COMMIT
BEGIN TRANSACTION
update tableName
set columnName = [something]
from
[subquery]
COMMIT
END
This doesn’t work because the column doesn’t exist after the commit.
Why doesn’t the COMMIT commit?
I’m guessing you are getting an error at parse stage, rather than at execute stage. The COMMIT will indeed commit, but the query parser isn’t as clever as the query execution engine, and all the parser knows is that it can see you referring to
tableName.columnName, which at parse time doesn’t exist.Wrap the whole
updatestatement in anEXEC:and you should be OK. Bear in mind that you will need to double up
's within the's of theEXEC.