SQL Server 2000:无效的列名称'bar'

时间:2016-09-22 10:24:21

标签: sql-server sql-server-2000

我想我刚刚在SQL Server 2000中发现了一个奇怪的错误。

以下查询返回错误

  

Msg 207,Level 16,State 3,Line 7
  列名称'bar'无效

如果我在SQL Server 2005中执行相同的确切查询,它将起作用。如果我select #weirdness.*,它也有效。是否有一些可以在程序中使用的解决方法?我知道go有帮助,但不能在程序中使用。顺便说一句,我们将摆脱SQL Server 2000,但这需要时间。

select 1 as  foo
into #weirdness;

alter table #weirdness add bar int identity;

--select  #weirdness.*    --works
select #weirdness.bar  --fails
from #weirdness;

系统:

  

Microsoft SQL Server 2000 - 8.00.2066(Intel X86)2012年5月11日18:41:14
  版权所有(c)1988-2003 Microsoft Corporation在Windows NT 5.2上的标准版(Build 3790:Service Pack 2)

2 个答案:

答案 0 :(得分:1)

以下是我现在可以想到的解决方法。

如果可能,请使用SQL Server 2005或更高版本。

如果可能,将脚本分成多个批次(在程序中不可能):

select  1   as  foo
into    #weirdness;

alter table #weirdness add bar int identity;

go  --split into multiple batches

--select  #weirdness.*    --works
select  #weirdness.bar  --fails
from    #weirdness;

首先创建表格:

create table #weirdness (
    foo bit
,   bar int identity
);

insert into #weirdness(foo)
select  1   as  foo;

select  #weirdness.bar
from    #weirdness;

答案 1 :(得分:1)

这不是一个错误,它记录了行为。试试这个尺寸:

select 1 as foo into #weirdness;
go
alter table #weirdness add bar int;
select #weirdness.bar
from #weirdness;

你会发现这在SQL Server 2005中也失败了,抱怨说" bar"不存在。

为什么会失败?因为,根据the documentation,您不允许这样做:

  

无法更改表,然后在中引用新列   同一批。

那么,为什么创建和更改表然后引用它仍然可以工作,如果我们在SQL Server 2005中一次批处理,而不是在SQL Server 2000中?这与语句重新编译有关,后者也在上面有记录,2005年是新的。

在SQL Server 2005中,由于#weirdness在批处理开始时不存在,因此SQL Server不会编译引用它的语句。执行select .. into,并将所有引用它的语句标记为重新编译。然后逐个编译和执行这些语句。当我们引用#weirdness.bar时,它已经被创建并且编译成功。

在SQL Server 2000中,由于#weirdness在批处理开始时不存在,因此SQL Server不会编译引用它的语句。执行select .. into,标记整个批次以进行重新编译。但是编译select #weirdness.bar失败,因为alter table尚未执行,批处理停止。

因此,文档应该实际读取"表格不能更改,然后在同一批次中引用新列,除非表格在批处理开始时根本不存在,那么您可以侥幸逃脱从SQL Server 2005开始,这些东西,但它可能不是一个热门的想法,依赖于"。你可以看出为什么他们更简单。