怎么做出以下的父子类关系的查询?

ccty3239968 2005-12-05 12:05:55
原来的表结构,都是char ,key1是子类,parent是父类
key1 parent text
1_ 0_ 闽东北区
2_ 0_ 闽西南区
4_ 1_ 闽东北一区
5_ 1_ 闽东北二区
8_ 2_ 闽西南二区
10_ 8_ 闽西北二区
以下增加了lbcode的查询,怎么做呢?谢谢
key1 parent text lbcode
1_ 0_ 闽东北区 0-1
2_ 0_ 闽西南区 0-2
3_ 0_ 营销本部 0-3
4_ 1_ 闽东北一区 0-1-4
5_ 1_ 闽东北二区 0-1-5
8_ 2_ 闽西南二区 0-2-8
10_ 8_ 闽西北二区 0-2-8-10

...全文
131 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ccty3239968 2005-12-05
  • 打赏
  • 举报
回复
厉害,谢谢,结贴
samfeng_2003 2005-12-05
  • 打赏
  • 举报
回复
create table t
(key1 varchar(5),parent varchar(5),[text] varchar(20))

insert t
select '1_','0_','闽东北区' union all
select '2_','0_','闽西南区' union all
select '4_','1_','闽东北一区' union all
select '5_','1_','闽东北二区' union all
select '8_','2_','闽西南二区' union all
select '10_','8_','闽西北二区'
go
create function f_go(@col varchar(5))
returns varchar(50)
as
begin
declare @i int
set @i=1
declare @t table (key1 varchar(5),parent varchar(5),[text] varchar(20),level int)
insert @t
select *,@i from t where key1=@col
while exists(select * from t a,@t b where a.key1=b.parent and b.level=@i)
begin
set @i=@i+1
insert @t
select a.*,@i from t a,@t b where a.key1=b.parent and b.level=@i-1
end
declare @sql varchar(50)
set @sql=''
select @sql=@sql+'-'+left(parent,patindex('%[^0-9]%',parent)-1) from @t order by level desc

return(stuff(@sql,1,1,''))
end
go

select *,dbo.f_go(key1)+'-'+left(key1,patindex('%[^0-9]%',key1)-1) as lbcode from t

drop function f_go
drop table t

key1 parent text lbcode
----- ------ -------------------- --------------------------------------------------------
1_ 0_ 闽东北区 0-1
2_ 0_ 闽西南区 0-2
4_ 1_ 闽东北一区 0-1-4
5_ 1_ 闽东北二区 0-1-5
8_ 2_ 闽西南二区 0-2-8
10_ 8_ 闽西北二区 0-2-8-10

(所影响的行数为 6 行)

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧