Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

ON clause that refers to 3 tables

$
0
0

Hi,

In a stored procedure at work, there is an ON clause that uses 3 tables, rather than 2, which doesn't look right.  Below is some code which attempts to simulate the situation.  The part that doesn't look right is the last line of the final ON clause that tries to join one table to two others.  The puzzling this is, in the stored procedures at work, rows are returned but in the example shown in the code below it does not return any rows.  I would not expect it to return rows but the fact that the SP at work is returning rows makes me second guess this instinct.  Unfortunately, I cannot post the code for the working SP due to confidentiality, which is why I tried to simulate it. Can anyone think of reasons why this approach may work sometimes and other times not?  What is the best way to make the join work in the example below?  Also, is there a name for this phenomenon in the ON clause?

--tables for example
declare @Plant table
(
  CompanyID int,
  PlantID int,
  WarehouseID int,
  primary key clustered (CompanyID, PlantID, WarehouseID)
);

declare @WarehouseItem table
(
  CompanyID int,
  WarehouseID int,
  ItemID int,
  StandardCost decimal(12,2),
  primary key clustered (CompanyID, WarehouseID, ItemID)
);

declare @ShopOrder table
(
  CompanyID int,
  PlantID int,
  OrderID int,
  ItemID int,
  OrderQuantity int,
  primary key clustered (CompanyID, PlantID, OrderID)
);

--sample data
insert into @Plant (CompanyID, PlantID, WarehouseID)
values
(1, 7, 54),
(1, 4, 28),
(1, 6, 20),
(2, 88, 401),
(2, 89, 402);

insert into @WarehouseItem (CompanyID, WarehouseID, ItemID, StandardCost)
values
(1, 7, 4444, 1.00),
(1, 7, 2222, 3.00),
(1, 6, 4444, 2.00),
(1, 4, 4444, 6.00),
(2, 88, 8888, 4.00),
(2, 89, 9999, 5.00);

insert into @ShopOrder (CompanyID, PlantID, OrderID, ItemID, OrderQuantity)
values
(1, 7, 90, 4444, 15),
(1, 7, 91, 4444, 6),
(1, 6, 90, 4444, 68),
(1, 6, 91, 4444, 10),
(1, 4, 93, 4444, 1),
(2, 88, 16, 8888, 30),
(2, 89, 16, 9999, 4);

--look at data
select * from @Plant;
select * from @WarehouseItem;
select * from @ShopOrder;

--weird join to pull standard cost together with shop order data
select
s.*,
w.StandardCost,
TotalCost = s.OrderQuantity * w.StandardCost
from @ShopOrder s
inner join @Plant p
on s.CompanyID = p.CompanyID
and s.PlantID = p.PlantID
inner join @WarehouseItem w
on s.CompanyID = w.CompanyID
and s.ItemID = w.ItemID
and p.WarehouseID = w.WarehouseID;  --this is the suspicious line
go


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>