表结构如下
ID parentid Name
1 0 大客车
2 1 金龙请问如何用一段sql文查询出如下结果
ID Name parentid parentName
2 金龙 1 大客车
ID parentid Name
1 0 大客车
2 1 金龙请问如何用一段sql文查询出如下结果
ID Name parentid parentName
2 金龙 1 大客车
解决方案 »
- [求助]如何禁止外部企业管理器注册本级数据库
- 从菜鸟到高手之二 --和YCZEALOT一起学习TSQL(The Guru's Guide To Transact SQL学习笔记)(yczealot)
- 如何新建一个服务器呢?新手,请多多关照!
- 存储过程-检索7天内数据,并将ID首次出现的数据同步到另一张表
- sql2005数据库订阅问题
- 没有服务器?
- ACCESS2000中SQL更新语句?
- select into 的问题(在线等)
- 附加数据库
- 请问高手一个关于SQLServer2000访问Exchange2000的问题,急!!!!
- 急急急!!!SQL跟踪器如何设置 能够跟踪到局域网中某一台电脑执行的SQL语句
- 关于产品,分类,品牌之间的查询!!!急
declare @t table(ID varchar(5) , NAME varchar(10), PID varchar(5))
insert into @t
select '0000', 'LVL1_1', NULL
union all select '0001', 'LVL2_1', '0000'
union all select '0002', 'LVL2_2', '0000'
union all select '0003', 'LVL3_1', '0001'
union all select '0004', 'LVL3_2', '0001'
union all select '0005', 'LVL3_3', '0002'
union all select '0006', 'LVL3_2_1', '0004'
if object_id('tempdb..#') is not null
drop table #select *
,flag = 0
into #
from @t
update a set
flag = 1
from # a
left join # b on a.id = b.pid
where b.pid is nulldeclare @lev int
set @lev = 1while @@rowcount >0
begin
set @lev = @lev+1
update a set
flag = case when @lev > a.flag then @lev else a.flag end
from # a
left join # b on a.id = b.pid
where b.flag = @lev-1
endselect * from #declare @sql1 varchar(1000)
declare @sql2 varchar(1000)
set @sql1 = 'select * from # a'+rtrim(@lev-1)
set @sql2 = ' where a'+rtrim(@lev-1)+'.pid is null'
while @lev>2
begin
set @sql1 = @sql1+' left join # a'+rtrim(@lev-2) +' on a'+rtrim(@lev-1) +'.id = a'+rtrim(@lev-2) +'.pid'
set @lev = @lev-1
end
exec (@sql1+@sql2)ID NAME PID flag ID NAME PID flag ID NAME PID flag ID NAME PID flag
----- ---------- ----- ----------- ----- ---------- ----- ----------- ----- ---------- ----- ----------- ----- ---------- ----- -----------
0000 LVL1_1 NULL 4 0001 LVL2_1 0000 3 0003 LVL3_1 0001 1 NULL NULL NULL NULL
0000 LVL1_1 NULL 4 0001 LVL2_1 0000 3 0004 LVL3_2 0001 2 0006 LVL3_2_1 0004 1
0000 LVL1_1 NULL 4 0002 LVL2_2 0000 2 0005 LVL3_3 0002 1 NULL NULL NULL NULL
给楼主参考
http://blog.csdn.net/canhui87/archive/2009/09/18/4566042.aspx
if object_id('tb') is not null
drop table tb
go
create table tb(ID int,parentid int,Name nvarchar(20))
goinsert into tb
select 1 ,0 ,'大客车' union all
select 2 ,1 ,'金龙'select a.ID,a.Name,b.id as parenntid,b.name as parentName
from tb a,tb b
where a.parentid = b.id
/*ID Name parenntid parentName
----------- -------------------- ----------- --------------------
2 金龙 1 大客车
*/