2012-11-02 30 views
0

我試圖創建一個從3個不同的表中獲取數據的SQL查詢。我的想法是使用CTE從2個表中收集信息,然後做一個正確的連接將數據添加到我的查詢的其餘部分。我需要從各個領域不同的數據帶來,但我遇到了臭名昭著的錯誤multi-part identifier could not be bound這是我到目前爲止已經寫的:CTE鏈接在不同的ID字段

with cte1 as 
(
SELECT   
[Physician ID] as InternalIdentifier, NPI, [Last Name] as LastName, [First Name]  
as  
FirstName, 
Physician_T1HYCPP.Specialty, DOB, Degree, Department, [State License Number], [UPIN Number],  
[Physician Status] 
FROM Physician_T1HYCPP left outer JOIN PhysicianFile 
on Physician_T1HYCPP.[Physician ID] = PhysicianFile.[TSI MD Number] 
where NPI <> '' 
), 
cteView 
AS 
(
Select [Doctor_Number], Address, City, State, Zip, Phone, Fax 
from V_PhysicianList 
) 
Select 
InternalIdentifier, NPI, LastName, FirstName, 
Specialty, DOB, Degree, Department, [State License Number], [UPIN Number], 
[Physician Status],  
[Doctor_Number], 
Address,City, State, Zip, Phone, Fax 
from cte1 
right outer join cteView on 
V_PhysicianList.[Doctor_Number] = PhysicianFile.[Doctor Number] 

下面是具體的錯誤:

Msg 4104, Level 16, State 1, Line 1 
The multi-part identifier "V_PhysicianList.Doctor_Number" could not be bound. 
Msg 4104, Level 16, State 1, Line 1 
The multi-part identifier "PhysicianFile.Doctor Number" could not be bound. 

的目標在這裏在第一個CTE中引入2個表中的所有字段,然後在第二個CTE的字段中「合併」,以便地址等在最終結果集中得到賦值。我如何確保來自cte1和cteView的字段能夠正確合併?

+0

你能發佈確切的錯誤消息,包括數字。 –

+0

你打賭。剛剛添加這些。 – SidC

+0

這裏有一點縮進會有很長的路要走...... – RBarryYoung

回答

2

在最後的SELECT中,您從CTE中選擇,但引用JOIN子句中的基表。只需使用正確的前綴:

Select 
InternalIdentifier, NPI, LastName, FirstName, 
Specialty, DOB, Degree, Department, [State License Number], [UPIN Number], 
[Physician Status],  
[Doctor_Number], 
Address,City, State, Zip, Phone, Fax 
from cte1 
right outer join cteView on 
cteView.[Doctor_Number] = cte1.[Doctor Number] 

但是,您還需要在cte1中包含該列。在最終選擇期間,SQL Server只能訪問其中提到的表,視圖或CTE,因此無法解析對基表的引用。