iT邦幫忙

0

刪除刪除X

刪除刪除刪除刪除刪除

1 個回答

2
rogeryao
iT邦大師 5 級 ‧ 2020-08-29 22:45:20
最佳解答

改下一行試試

SELECT level,id,@SearchTerm as ProductName,Parent,Child FROM  cte ;

或是改

DECLARE @SearchTerm NVARCHAR(10) = N'carA';
DECLARE @Table AS TABLE ( id INT, product1 NVARCHAR(10), product2 NVARCHAR(10));

INSERT INTO @Table
VALUES ( 1, 'carA', 'Tire' )
,      ( 2, 'carA', 'meter' )
,      ( 3, 'Tire', 'tireA' )
,      ( 4, 'Tire', 'tireB' )
,      ( 5, 'meter', 'meterA' )
,      ( 6, 'meter', 'meterB' )
,      ( 7, 'meter', 'meterC' )
,      ( 8, 'meterC', 'meterCC' );


WITH cte AS ( SELECT    1           AS level
              ,         T1.id
              ,@SearchTerm as ProductName
              ,         T1.product1 Parent
              ,         T1.product2 Child
                FROM    @Table T1
               WHERE T1.product1 = @SearchTerm
              UNION ALL
              SELECT    cte.level + 1
              ,         T2.id
              ,@SearchTerm as ProductName
              ,         T2.product1 Parent
              ,         T2.product2 Child
                FROM    @Table T2
                JOIN cte ON cte.Child = T2.product1 )
                
SELECT  *  FROM  cte ;

Demo

沒想到這樣做就可以了~感恩

我要發表回答

立即登入回答