34,693
社区成员
发帖
与我相关
我的任务
分享
DECLARE @T TABLE (ID INT,start VARCHAR(20),[end] VARCHAR(20))
INSERT INTO @T(ID,start,[end])
SELECT 1,'A','B' UNION ALL
SELECT 2,'B','D' UNION ALL
SELECT 3,'E','F' UNION ALL
SELECT 4,'D','M' UNION ALL
SELECT 5,'B','K' UNION ALL
SELECT 6,'G','W'
;WITH tb AS
(
SELECT
start,
[end],
routes=cast(start+','+[end] as varchar(8000))
FROM @T WHERE start='B'
UNION ALL
SELECT
A.start,
B.[end],
A.routes+','+B.start
FROM tb AS A
JOIN @T AS B ON A.[end]=B.start
)
SELECT * FROM tb
DECLARE @T TABLE (ID INT,start VARCHAR(20),[end] VARCHAR(20))
INSERT INTO @T(ID,start,[end])
SELECT 1,'A','B' UNION ALL
SELECT 2,'B','D' UNION ALL
SELECT 3,'E','F' UNION ALL
SELECT 4,'D','M' UNION ALL
SELECT 5,'B','K' UNION ALL
SELECT 6,'G','W'
;WITH tb AS
(
SELECT
start,
[end],
routes=CAST(start+','+[end] AS VARCHAR(MAX))
FROM @T WHERE start='B'
UNION ALL
SELECT
A.start,
B.[end],
CAST(A.routes+','+B.start AS VARCHAR(MAX))
FROM tb AS A
JOIN @T AS B ON A.[end]=B.start
)
SELECT * FROM tb