SQL tree data struct(4): AdjList2MatPath (for printing tree struct)



if object_id('proc_print_tree') is not null
    drop procedure proc_print_tree
go

create procedure proc_print_tree @raw_data_sql nvarchar(1000), @debug bit = 0
with encryption
as
    if object_id('tempdb..#adjacency_list') is not null
        drop table #adjacency_list
    create table #adjacency_list(code nvarchar(30) collate database_default, parent nvarchar(30) collate database_default)
    if @debug = 1 print @raw_data_sql
    insert #adjacency_list exec(@raw_data_sql)

    if @debug = 1 select [data]='', * from #adjacency_list

    if object_id('tempdb..#materialized_path') is not null
        drop table #materialized_path   
    create table #materialized_path( code nvarchar(30) collate database_default, parent nvarchar(30) collate database_default,
        height int, path nvarchar(3900) collate database_default)

    declare @level int
    select @level = 0
    insert #materialized_path select code, null, 0, code from #adjacency_list where parent is null
    while @@rowcount > 0
    begin
        select @level = @level + 1
        insert into #materialized_path
        select b.code, b.parent, @level, a.path + b.code
        from #materialized_path a inner join #adjacency_list b on a.code = b.parent -- can not use left join!!!
        where height = @level-1 and b.parent <> b.code
    end

    if @debug = 1 select [tree]='', * from #materialized_path order by path

    if not exists(select * from #materialized_path)
    begin
        print 'no data exists in #materialized_path!'
        return
    end
   
    declare @h int, @i int, @sql nvarchar(1000)
    select @h = (select max(height) from #materialized_path), @i = 0, @sql = '0'
    while @i <= @h
        select @sql = @sql + ',case height when ' + cast(@i as varchar) +
            ' then code else '''' end as hierarchy_level_' + cast(@i as varchar) + char(13),
            @i = @i + 1

    set @sql = 'select '  + char(13) + substring(@sql, 3, 1000) + char(13) + ' from #materialized_path order by path'
    if @debug = 1 print @sql
    exec(@sql)

    drop table #adjacency_list, #materialized_path
go

/*
print isnull(object_id('tempdb..#adjacency_list'), -1)
print isnull(object_id('tempdb..#temp'), -1)

exec proc_print_tree
'select distinct object_name(rkeyid), NULL
from sysreferences a
where not exists (select * from sysreferences b where a.rkeyid = b.fkeyid)
union all
select object_name(fkeyid), object_name(rkeyid) from sysreferences
'

exec proc_print_tree
'select ''APDocA'', NULL
union all
select object_name(fkeyid), object_name(rkeyid) from sysreferences
', 1
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值