不同ID字段的CTE链接

时间:2012-11-02 21:49:34

标签: sql-server tsql common-table-expression

我正在尝试创建一个从3个不同表中获取数据的SQL查询。我的想法是使用CTE从2个表中收集信息,然后进行右连接以将数据添加到我的查询的其余部分。我需要从每个字段引入不同的数据,但我遇到了臭名昭着的错误multi-part identifier could not be bound这是我到目前为止写的:

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中的两个表中引入所有字段,然后在第二个CTE的字段中“合并”,以便在最终结果集中对地址等进行评估。如何确保cte1和cteView中的字段合并正确?

1 个答案:

答案 0 :(得分: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,因此无法解析对基表的引用。