首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

重分求SQL语句!该如何处理

2012-01-07 
重分求SQL语句!!!!!!!!!!!!!!!!!!!!我有个树状图,节点数据库的字段分为code(代码),level(层次),upcode(父

重分求SQL语句!!!!!!!!!!!!!!!!!!!!
我有个树状图,  
节点数据库的字段   分为   code(代码)   ,level(层次),   upcode(父节点代码)

比如
code             level       upcode
01                       1             null
0101                   2               01
02                       1             null
0201                   2               02
0202                   2               02
020203               3               0202
...

我现在用一个SQL语句得到每个节点的第1层次的父节点代码
比如按照上面数据得到
code               firstupcode
01                   01
0101               01
02                   02
0201               02
0202               02
020203           02
不要用   left(code,2)因为可能节点代码不是这样按照规矩的

[解决办法]
对不起,没看到你要递归,恐怕要写存储过程了.

要不然你就要一百几十张表自关联
[解决办法]
set nocount on
declare @a table(code varchar(10), level int, upcode varchar(20),firstdot varchar(10),levelx int)
insert @a select '01 ', 1 , null,null,null
union all select '0101 ', 2 , '01 ',null,null
union all select '02 ', 1 ,null,null,null
union all select '0201 ', 2 , '02 ',null,null
union all select '0202 ', 2 , '02 ',null,null
union all select '020203 ', 3 , '0202 ',null,null
union all select '02020304 ', 4 , '020203 ',null,null

declare @i int
select @I=max(level) from @a

update @a set upcode=code where upcode is null
update @a set levelx=level,firstdot=upcode

while @i> 0
begin
update a set firstdot=b.firstdot,levelx=@i-1 from @a a ,@a b where a.firstdot=b.code and a.levelx=@I
set @i=@i-1
end

select * from @a

热点排行