我正在尝试创建一个视图,该视图将返回3个级别的数据字符串。
select bf.functionName + ' \ ' + ISNULL(bf1.functionName + ' \ ', '') + ISNULL(bf2.functionName, '') from tblBusinessFunction bf
inner join tblBusinessFunction bf1 on bf1.parentID = bf.id and bf.level = 0
inner join tblBusinessFunction bf2 on bf2.parentID = bf1.id and bf1.level = 1
以上仅返回顶级祖父母和父母而非子级别。
这就是表格的样子
| id | functionName | parentID | level |
|:-----|----------------------------:|:--------:|:-------:|
| 101 | Portfolio Strategy Functions| NULL | 0 |
| 110 | Research | 101 | 1 |
| 111 | Economic Forecasting | 110 | 2 |
现在我的查询将返回Portfolio Strategy Functions \ Research \ Economic Forecasting
,但我希望它也返回Portfolio Strategy Functions \ Research
,但它不会做。{/ p>
答案 0 :(得分:2)
我试图解决
declare @T table ( id int, functionName varchar(50), parentid int, level int )
insert @T
values
(101,'Portfolio Strategy Functions',null,0),
(110,'Research',101,1),
(111,'Economic Forecasting',110,2)
;with Outline as
( select id,level,functionName = convert(varchar(max),functionName) from @T where level = 0
union all
select T.ID, T.level, functionName = O.functionName +' / '+ T.functionName from @T T
join Outline O on O.id = T.parentid
)
select * from OutLine
where level > 0
这是结果
(3 row(s) affected)
id level functionName
----------- ----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
110 1 Portfolio Strategy Functions / Research
111 2 Portfolio Strategy Functions / Research / Economic Forecasting
(2 row(s) affected)