2016-09-22 59 views
1

我想我只是發現了SQL Server的一個奇怪的錯誤2000的SQL Server 2000:無效的列名稱 '欄'

下面的查詢將返回錯誤

消息207,級別16,狀態3 ,7號線
無效的列名「酒吧」

如果我執行在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(英特爾X86)2012 5月11日18時41分十四秒
版權所有(c)關於1988 - 2003年的Windows微軟公司標準版NT 5.2(Build 3790:Service Pack 2)

回答

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

這是不是一個錯誤,它是記錄的行爲。試試這個尺寸:

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開始,但它可能不是一個如此熱門的想法,依靠它「。你可以看到爲什麼他們保持簡單。