0

我正在尝试创建一个从 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 中的 2 个表中引入所有字段,然后“合并”来自第二个 CTE 的字段,以便地址等在最终结果集中得到重视。如何确保 cte1 和 cteView 中的字段正确合并?

4

1 回答 1

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,因此它无法解析对基表的引用。

于 2012-11-02T22:23:48.793 回答