views:

36

answers:

1

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?

+2  A: 

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 update statement in an EXEC:

EXEC ('
        update tableName
        set columnName = [something]
        from 
            [subquery]
')

and you should be OK. Bear in mind that you will need to double up 's within the 's of the EXEC.

AakashM
I'm getting at execute time too.
borisCallens
Exec-ing indeed works. Sure there must be a better way to get this done then execing everything?
borisCallens
The best thing is to not have to add table columns on the fly. (We *have* to do it in a project I'm working on now, and it's really, truly, and amazingly awkward.)
Philip Kelley
Well, a project that has been running for quite a while now has to be altered to support another column table. This isn't that an exotic request I imagine..
borisCallens
Ah, if this this is a one-time script used to update an existing system, that's standard.
Philip Kelley
Well off course. Do you mean your system is adding (and removing I imagine) columns at runtime on regular basis?
borisCallens