バス停のグラフの再帰的トラバーサル (MSSQL 2016 でテスト済み):
DECLARE @from NCHAR(4) = 'ort1';
DECLARE @to NCHAR(4) = 'ort9';
WITH [route] ([path], [lastBus], [current])
AS
(SELECT CAST(N'' AS NVARCHAR(1000)) AS [path], CAST(N'' AS NCHAR(2)) AS [lastBus], @from AS [current]
UNION ALL
SELECT CAST( cur.[path] + N',' + busesAvailable.name + N' to ' + [next].stat AS NVARCHAR(1000)) AS [path],
busesAvailable.name AS [lastBus],
[next].stat AS [current]
FROM [route] cur
INNER JOIN dbo.BusStat busesAvailable ON busesAvailable.stat = cur.[current] AND busesAvailable.name <> cur.[lastBus]
INNER JOIN dbo.BusStat [next]
ON [next].stat <> cur.[current]
AND [next].name = busesAvailable.name)
SELECT TOP 1 [route].[path]
FROM [route]
WHERE [route].[current] = @to;
テーブルを考慮すると、次のように作成されます。
CREATE TABLE [dbo].[BusStat]
(
[name] NCHAR (2) NOT NULL,
[stat] NCHAR (4) NOT NULL
);
INSERT INTO [dbo].[BusStat] ([name], [stat])
SELECT 'b1', 'ort1' UNION ALL
SELECT 'b1', 'ort2' UNION ALL
SELECT 'b1', 'ort3' UNION ALL
SELECT 'b2', 'ort7' UNION ALL
SELECT 'b2', 'ort8' UNION ALL
SELECT 'b2', 'ort9' UNION ALL
SELECT 'b3', 'ort3' UNION ALL
SELECT 'b3', 'ort4' UNION ALL
SELECT 'b3', 'ort5' UNION ALL
SELECT 'b3', 'ort6' UNION ALL
SELECT 'b3', 'ort7';