如果是SQL2005以上则可以用CTE递归写法
use tempdb
go
create table #emp
(eid integer not null,
ename varchar(10) not null,
epid integer null,
)
insert into #emp
select 1,'A',5
union all
select 2,'me',3
union all
select 3,'bos',4
union all
select 4,'boss',null
select * from #emp
;with empcte as
(select epid,(select ename from #emp b where b.eid = a.epid) as name from #emp a where ename = 'me'
union all
select b.epid,(select ename from #emp where eid = b.epid) as name from empcte a join #emp b on a.epid = b.eid
)
select * from empcte where epid is not null
是查上级和上上级的ID吗,如果是语句
SELECT t1.Eid, t1.ename, t1.epid, t2.epid as sepid FROM employees t1 INNER JOIN employees t2 ON t1.epid = t2.Eid WHERE t1.ename='me'
我去,都这么猛。不过真正的写法是用递归查询。在ORACLE中,写法还算简单。自己查吧,养成一个自己动手解决问题的习惯,真的。