递增地添加字符串类型的列的行值

Add incrementally row values of a column of type string

我有一个 table 具有以下值

 UserID   ParentID  Levels  Path
   1        NULL      0     A1
   5        1         1     A2
   9        5         2     A3
   43       9         3     A4

输出应该如下所示:

 UserID   ParentID  Levels  FinalPath
   1        NULL      0     A1/
   5        1         1     A1/A2/
   9        5         2     A1/A2/A3/
   43       9         3     A1/A2/A3/A4/

提前感谢您对此的任何指导。

使用递归通用 table 表达式的解决方案。

示例数据

create table users
(
  userid int,
  parentid int,
  levels int,
  path nvarchar(100)
);

insert into users (userid, parentid, levels, path) values
(1,  NULL, 0, 'A1'),
(5,  1,    1, 'A2'),
(9,  5,    2, 'A3'),
(43, 9,    3, 'A4');

解决方案

with cte as
(
  select u.userid, u.parentid, u.levels, u.path
  from users u
  where u.parentid is null
    union all
  select u.userid, u.parentid, u.levels, convert(nvarchar(100), c.path + '/' + u.path)
  from users u
  join cte c
    on c.userid = u.parentid
)
select c.userid, c.parentid, c.levels, c.path + '/' as FinalPath
from cte c;

Fiddle

这是一个既计算Level又附加Path的版本。

数据

drop table if exists dbo.test_table;
go
create table dbo.test_table(
  UserID          int,
  ParentID         int,
  [Path]            varchar(5));
                    
insert dbo.test_table([UserID], [ParentID], [Path]) values
(1,null, 'A1'),
(5,1, 'A2'),
(9,5, 'A3'),
(43,9, 'A4');

查询

;with recur_cte([UserId], [ParentID], h_level, [Path]) as (
    select [UserId], [ParentID], 0, cast([Path] as varchar(100))
    from dbo.test_table
    where [ParentID] is null
    union all
    select tt.[UserId], tt.[ParentID], rc.h_level+1, cast(concat(tt.[Path], '/', rc.[Path]) as varchar(100)) 
    from dbo.test_table tt join recur_cte rc on tt.[ParentID]=rc.[UserId])
select * from recur_cte;

结果

UserId  ParentID    h_level Path
1       NULL        0       A1
5       1           1       A1/A2
9       5           2       A1/A2/A3
43      9           3       A1/A2/A3/A4