在 temp table 中使用由 alter table 添加的新列不起作用

using new columns in the temp table added by alter table not work

我有一个问题,新添加的列不能在进一步的评论中使用。

我有一个由 "select into" 构建的临时 table,然后我需要由 "alter table" 添加一个标识列。但是当我想在 "join" 中使用新列时,出现错误 "Invalid column"。请注意,这些命令可以单独使用。

我认为原因是,编译器没有找到新列,它在 运行 之前给出错误。 有解决方案吗?

我在 sql server 2000 中遇到过这个问题,似乎在较新的版本中,问题不存在。

create table #tmp_tb
(name varchar(4), val int)
insert into #tmp_tb values('ab',1);
insert into #tmp_tb values('abc',2);
select * from #tmp_tb
alter table #tmp_tb add id int NOT NULL IDENTITY(1,1);
select * from #tmp_tb
select id,name,val from #tmp_tb

发生错误:

Msg 207, Level 16, State 3, Line 9 Invalid column name 'id'.

将最后一行替换为

EXECUTE sp_executesql N'select id,name,val from #tmp_tb';

确实,解析器还不知道新列。通过 sp_executesql 传递它可以避免这种情况。