我只有2年的SQL经验,并且试图从下表中简化层次结构,但没有通过。感谢您的宝贵建议。
要求是显示类似'bala>>ben>>mari>>dir>>cto>>ceo>>null'
我尝试过,但是没有运气。
declare @cn varchar(25), @mn varchar(25), @vr varchar(25), @tm varchar(25), @msg varchar(max);
declare crsr cursor for
select * from dbo.ctable ct order by ename
open crsr
fetch next from crsr into @cn, @mn
set @msg = @cn
while @@FETCH_STATUS = 0
begin
if @mn is not null set @msg = @msg + ' - '+@mn
print @msg
fetch next from crsr into @cn, @mn
end
close crsr
deallocate crsr
答案 0 :(得分:0)
我必须构造这个简单的查询,满足我的要求。希望可以对此进行进一步的微调,对您有所帮助。 thnx
select c.ename Emp, c.mname Lvl1, isnull(c1.mname,'') Lvl2,
isnull(c2.mname,'') Lvl3,isnull(c3.mname,'') Lvl4,isnull(c4.mname,'')
Lvl5,isnull(c5.mname,'') Lvl6
,c.ename+' >> '+c.mname+' >> '+isnull(c1.mname,'')+' >>
'+isnull(c2.mname,'')+' >> '+isnull(c3.mname,'')+' >>
'+isnull(c4.mname,'')+' >> '+isnull(c5.mname,'')
from ctable c
left join ctable c1 on c.mname=c1.ename
left join ctable c2 on c1.mname=c2.ename
left join ctable c3 on c2.mname=c3.ename
left join ctable c4 on c3.mname=c4.ename
left join ctable c5 on c4.mname=c5.ename
left join ctable c6 on c5.mname=c6.ename