A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Hi @petr p ,
Welcome to Microsoft Q&A!
You could use the Recursive CTE and please refer below query and check whether it is working.
create table #temp
(
OrderID char(2),
PreviousOrderID char(2),
OrderName varchar(20),
OrderDate date
)
insert into #temp values
('10','07','Vegetable', '2021-08-18'),
('09','03','Meat','2021-08-16'),
('08',null,'Meat','2021-08-14'),
('07','05','Vegetable','2021-08-12'),
('06',null,'Nuts','2021-08-10'),
('05','03','Vegetable','2021-08-08'),
('04','03','Vegetable','2021-08-06'),
('03',null,'Vegetable','2021-08-04')
;WITH cte AS (
SELECT OrderID, PreviousOrderID, OrderName, OrderDate
FROM #temp
WHERE OrderID =10
UNION ALL
SELECT a.OrderID, a.PreviousOrderID,a.OrderName,a.OrderDate
FROM #temp a
INNER JOIN cte b
ON b.PreviousOrderID = a.OrderID
)
SELECT * FROM cte;
Output:
OrderID PreviousOrderID OrderName OrderDate
10 07 Vegetable 2021-08-18
07 05 Vegetable 2021-08-12
05 03 Vegetable 2021-08-08
03 NULL Vegetable 2021-08-04
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.