SQL Server:从单个表中获取所有父子URL

时间:2010-09-28 16:23:53

标签: sql sql-server tsql sql-server-2008

我有一个看起来像这样的表:

Slug | Parent | MetaTitle | MetaDescription | MetaKeywords

只要父级不为空,就可以通过将slug附加到父级来构建网站上的Url。所以,如果我有这样的数据:

Slug            | Parent
-----------------------------------------
Home              null
About             null
Our-Company       About
Our-History       Our-Company

我希望能够运行一个能让我

的查询
/Home
/About
/About/Our-Company
/About/Our-Company/Our-History

这可能吗?任何帮助都会很棒!!!

1 个答案:

答案 0 :(得分:4)

可以使用recursive CTE

declare @URLTable table (
 Slug varchar(50),
 Parent varchar(50)
)

insert into @URLTable
 (Slug, Parent)
 values
 ('Home', null),
 ('About', null),
 ('Our-Company', 'About'),
 ('Our-History', 'Our-Company')


;with cteURLs as (
 select Slug, cast('/' + Slug as varchar(1000)) as URL
     from @URLTable
     where Parent is null
 union all
 select u.Slug, cast(c.URL + '/' + u.Slug as varchar(1000)) as URL
     from @URLTable u
         inner join cteURLs c
             on u.Parent = c.Slug
)
select URL from cteURLs

输出结果为:

URL
-----------------
/Home
/About
/About/Our-Company
/About/Our-Company/Our-History