views:

620

answers:

2

SQL Server 2005.

The following 3 lines of sql work without error if the Is_Active column had previously existed in the Dim_Form table.

ie if Is_Active has not existed previously, running the following 3 lines gives an error as displayed below;

ALTER TABLE dbo.Dim_form add Is_Active bit NULL 
UPDATE dbo.Dim_form set Is_Active = 1
ALTER table dbo.Dim_form alter column Is_Active bit NOT NULL

I get this error only if its a 'brand new' column

Msg 207, Level 16, State 1, Line 2
Invalid column name 'Is_Active'.

If I run this

ALTER TABLE dbo.Dim_form add Is_Active bit NULL 
GO

UPDATE dbo.Dim_form set Is_Active = 1
ALTER TABLE dbo.Dim_form alter column Is_Active bit NOT NULL 

-- and now drop the newly created column
ALTER TABLE dbo.Dim_form DROP COLUMN Is_Active

Now I can run the original 3 lines of sql successfully - any ideas what is happening with this?

Why would the prior existence of a column have an effect on the script?

+1  A: 

When the SQL Is parsed in the first version the column doesn't exist. So the Parsing phase fails.

In the second version you are splitting the SQL up in to separate batches, so each batch is parsed on its own. The first batch creates the column, the second batch is then parsed prior to running and everything is okay because the column now exists.

Colin Mackay
ok you run the first 'two batches'.. that bit makes sense, but what about the 'third batch' ie after successfully creating the column, you delete it, then run the original 3 lines at the same time again.. it works without error.
Paul Rowland
In the "third batch" you are dropping the Is_Active column and running the 3 original lines. When the batch is parsed the Is_Active column exists, even although part way through it will cease to exist, but the parser doesn't see that because all it can see is the state of the SQL Server at the point it parses the batch.
Colin Mackay
ok thanks but, where does the Is_Active column still exist after dropping it? I have dropped the column, closed the connection, opened up a new query window, ran the original 3 lines and they still work.
Paul Rowland
A: 

This doesnt answer my question, but is the script I used that worked consistently whether or not the Is_Active column had existed previously in a table.

    ALTER TABLE dbo.Dim_form
        ADD Is_Active bit NOT NULL
           CONSTRAINT TEMP_ISACTIVE_CONSTRAINT_Dim_form DEFAULT 1

    ALTER TABLE dbo.Dim_form
        DROP CONSTRAINT TEMP_ISACTIVE_CONSTRAINT_Dim_form
Paul Rowland