2

I've got a self referencing table (in SQL Server):

Page
==========
Id: int
RelativeUrl: nvarchar(max)
ParentId: int -> FK to pageId

Example data:

ID | RelativeUrl | ParentId
===============================
1  | /root       | null
2  | /test1      | 1
3  | /test2      | 1
4  | /test3      | 1
5  | /test1-1    | 2
6  | /test1-2    | 2
7  | /test1-1-1  | 5

I want to create an sql query to retrieve all pages of the table with FULL relative url. I thought about using a recursive SQL query, but don't know how to concat the relativeurl to make it a full relative url.

Wanted result:

ID | FullRelativeUrl                | ParentId
===================================================
1  | /root                          | null
2  | /root/test1                    | 1
3  | /root/test2                    | 1
4  | /root/test3                    | 1
5  | /root/test1/test1-1            | 2
6  | /root/test1/test1-2            | 2
7  | /root/test1/test1-1/test1-1-1  | 5
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
RubenHerman
  • 1,674
  • 6
  • 23
  • 42

1 Answers1

2

You can use a recursive CTE:

with cte as (
      select id, convert(varchar(max), relativeurl) as url, 1 as lev
      from page
      where parentid is null
      union all
      select p.id, concat(cte.url, p.relativeurl), lev + 1
      from cte join
           page p
           on p.parentid = cte.id
     )
select cte.*
from cte;

Here is a db<>fiddle.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • 1
    If the slashes are part of the data, you don't need to concat on another, you'll end up with /root//test1... – Andrew Mar 12 '20 at 14:40