Here is my script. Let's say I have two tables "Car" and "Karpart". A car consists of many parts, and each part can belong to several cars. One of the complications in my case is that each part gets a new PartID, even if it's the same name, but it just belongs to a different car. This is something that I can’t control, so bear with me. Here is the script to configure.
IF OBJECT_ID('Car') IS NOT NULL DROP TABLE Car
CREATE TABLE Car (
CarID INT,
CarName VARCHAR(16)
)
IF OBJECT_ID('CarPart') IS NOT NULL DROP TABLE CarPart
CREATE TABLE CarPart (
PartID INT,
PartName VARCHAR(16),
CarID INT
)
INSERT INTO Car
VALUES (1, 'Chevy'),
(2, 'Ford'),
(3, 'Toyota'),
(4, 'Honda'),
(5, 'Nissan'),
(6, 'Hugo')
INSERT INTO CarPart
VALUES (110, 'Engine', 1),
(120, 'Engine', 2),
(210, 'Door', 1),
(220, 'Door', 3),
(310, 'Seat', 4),
(320, 'Seat', 5),
(410, 'Window', 3),
(510, 'Wheel', 2),
(420, 'Window', 6)
As you can see, the Engine part belongs to both Chevy and Ford and is listed twice with different identifiers. Once again, this is a design limitation that I have to live with.
: , , , . , . : @StartCar → @StartCar → → "" → , "" - → , .
, :
DECLARE @StartCar VARCHAR(16) = 'Chevy'
;WITH cte (CarName, PartName)
AS
(
SELECT c.CarName,
cp.PartName
FROM CarPart cp
JOIN Car c ON cp.CarID = c.CarID
WHERE c.CarName = @StartCar
UNION ALL
SELECT c.CarName,
cp.PartName
FROM CarPart cp
JOIN Car c ON cp.CarID = c.CarID
JOIN cte cte ON cp.PartName = cte.PartName
)
SELECT CarName, PartName
FROM cte
. , :
CarName PartName
Chevy Engine
Chevy Door
Ford Engine
Ford Wheel
Toyota Door
Toyota Window
Hugo Window
.
!