Somehow this works when I put it into SQL Server 2008 R2 Management Studio:
if 1 = 1
begin
create table foo (
p int
);
alter table foo
add v int;
insert into foo values (1, 2)
select v from foo;
end
GO
This says invalid column name v:
create table foo (
p int
);
go;
if 1 = 1
begin
/* create table foo (
p int
);*/
alter table foo
add v int;
insert into foo values (1, 2)
select v from foo;
end
GO
This works fine:
create table foo (
p int
);
go
if 1 = 1
begin
/* create table foo (
p int
);*/
alter table foo
add v int;
insert into foo values (1, 2)
-- select v from foo;
end
GO
Here is another example and it works fine too:
create table foo (
p int
);
go
if 1 = 1
begin
alter table foo
add v int not null;
alter table foo
add constraint PK_foo primary key(v);
end
GO
It's clearly said in doc: http://technet.microsoft.com/en-us/library/ms175502(v=sql.105).aspx
A table cannot be changed and then the new columns referenced in the same batch.
It seems that if table is created inside batch that's fine, or if you're creating constraint for added column in the batch that's fine too. But if you're issuing DML query (select) for that column, you'll get an error.
Why does it behave like this?