2013-12-10 55 views
0

請參閱以下查詢。SQL Server 2012中模糊的列名稱錯誤

select UserStatus,UserStatus from ((Select 'Active' as UserStatus) 
union (Select 'Inactive' as UserStatus))a order by UserStatus 

錯誤:

Msg 209, Level 16, State 1, Line 3 
Ambiguous column name 'UserStatus' 

解決方案:

ALTER DATABASE VCarePortal 
SET COMPATIBILITY_LEVEL = 100 

90 = SQL Server 2005`enter code here` 
100 = SQL Server 2008 and SQL Server 2008 R2 
110 = SQL Server 2012. 

我試圖關於兼容性水平模式。但我仍然有模棱兩可的錯誤。

+0

你試圖得到什麼結果? – Greg

+0

你的預期結果是什麼。你想要兩個列還是一個標題欄也可以嗎? –

回答

1

您正在選擇同一列兩次,刪除一個並解決問題。無論如何,由於每個聯合選擇只返回一列,因此您不需要這樣做。

select UserStatus from ((Select 'Active' as UserStatus) 
union (Select 'Inactive' as UserStatus))a order by UserStatus 
2

請刪除一個UserStatus和嘗試:

select UserStatus from 
(
    (Select 'Active' as UserStatus) 
    union 
    (Select 'Inactive' as UserStatus) 
)a order by UserStatus 
0

這裏歧義產生,而您訂購的同一列,所以SQL引擎不理解這列需要訂購。

因此,使用下面的查詢將解決您的問題。

-- Order by 1 means order with first column in selection 
select UserStatus, UserStatus 
from (
(Select 'Active' as UserStatus) 
union 
(Select 'Inactive' as UserStatus) 
)a order by 1 


-- Or remove duplicate column from selection. 
select UserStatus 
from (
(Select 'Active' as UserStatus) 
union 
(Select 'Inactive' as UserStatus) 
)a order by UserStatus