简体   繁体   中英

SQL - Invalid column name, but it exists

Im getting an error when trying to use inner join.

Invalid column name 'SupplierID'.

The column exists in both tables.

select p.ProductID, s.CompanyName, od.orderID
from OPENROWSET('SQLOLEDB', 'Server=DESKTOP-509LB9L\MSSQLSERVER01;Trusted_Connection=yes;',
   'select ss.CompanyName from northwind.dbo.suppliers ss') s
   inner join [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
on s.SupplierID = p.SupplierID
    inner join northwind.dbo.[Order Details] od
on od.ProductID = p.ProductID
    inner join northwind.dbo.Orders o
on od.OrderID = o.OrderID

Expected results:

ProductID    CompanyName     OrderID      UnitPrice      Quantity
1            Exotic Liquids   10249        42,40            35
2            Mayumi's         10250        35,40            10
3            Pavlova, Ltd.    10255        18,60            22

You need to select SupplierID in OPENROWSET . If you are joining two tables without selecting a columns that is why you receiving an error.

Just add ss.SupplierID with ss.CompanyName as following

select ss.SupplierID, ss.CompanyName from northwind.dbo.suppliers ss

You have to select the respective column SupplierID in your sub query,

select p.ProductID, s.CompanyName, od.orderID
from OPENROWSET('SQLOLEDB', 'Server=DESKTOP- 
509LB9L\MSSQLSERVER01;Trusted_Connection=yes;',
'select ss.CompanyName, SS.SupplierID from northwind.dbo.suppliers ss') s
inner join [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
on s.SupplierID = p.SupplierID
inner join northwind.dbo.[Order Details] od
on od.ProductID = p.ProductID
inner join northwind.dbo.Orders o
on od.OrderID = o.OrderID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM