我试图查看是否可以从同一个表中的父关系中获取值。
在下面的示例中,Parent_ID
是与父母的关系。
理想情况下,RouteName
应该是一个计算字段,用于选择直接父级的路由名(或名称,如果为空)。
这样,我可以通过只选择直接父级来创建一个完整的路径,并且可以在所有记录中保存迭代或CTE。 这可能吗?
+----+------------------+-------------------------------------+-----------+
| ID | Name | RouteName | Parent_ID |
+----+------------------+-------------------------------------+-----------+
| 1 | Parent | NULL | |
+----+------------------+-------------------------------------+-----------+
| 2 | Child 1 | Parent - Child 1 | 1 |
+----+------------------+-------------------------------------+-----------+
| 3 | Child of Child 1 | Parent - Child 1 - Child of Child 1 | 2 |
+----+------------------+-------------------------------------+-----------+
答案 0 :(得分:1)
您可以使用计算列的函数
drop table MyTable
drop function dbo.fn_CalculateRouteName
create table MyTable
(
ID int,
Name varchar(100),
Parent_ID int
)
go
create function dbo.fn_CalculateRouteName(@ID int)
returns varchar(max)
begin
declare @rtn varchar(max);
with cte (ID, Name) as (
select Parent_ID, convert(varchar(max), Name) From MyTable where ID = @ID
union all
select MyTable.Parent_ID, convert(varchar(max), MyTable.Name + ' - ' + cte.Name )
from cte
inner join MyTable on cte.Id = MyTable.ID
)
select @rtn = max(Name)
from cte
return @rtn
end
go
alter table MyTable add RouteName AS dbo.fn_CalculateRouteName(ID);
insert into MyTable(ID, Name, Parent_ID) values(1, 'Parent', null);
insert into MyTable(ID, Name, Parent_ID) values(2, 'Child 1', 1);
insert into MyTable(ID, Name, Parent_ID) values(3, 'Child of Child 1', 2);
select * from MyTable