• SQLServer实现树型结构数据查询的存储过程,类似oracle的connect by


    CREATE PROCEDURE [dbo].[sp_get_tree_relation]
    (@table_name nvarchar(50), @id nvarchar(50), @name nvarchar(50), @parent_id nvarchar(50), @startId nvarchar(20))
    AS
        declare @v_id int
        declare @v_level int
        declare @sql nvarchar(500)
    begin
        create table #temp (id nvarchar(20),name nvarchar(50),parent_id nvarchar(20))
        create table #t1 (id nvarchar(20),name nvarchar(50),parent_id nvarchar(20),level int)
        -- 将需要查询关系的表的数据先导入到临时表
        set @sql='insert into #temp select '+@id+','+@name+','+@parent_id +' from '+@table_name
        exec sp_executesql @sql

        set @v_level=1
        set @v_id=@startId
        insert #t1 select a.id,a.name,a.parent_id,@v_level from #temp a where a.id=@v_id
        while @@rowcount>0
        begin
            set @v_level=@v_level+1
            insert #t1 select a.id,a.name,a.parent_id,@v_level
            from #temp a where a.parent_id in
            (select id from #t1 where level=@v_level-1)
        end

        select a.level,a.id,a.name,a.parent_id,b.name parent_name
        from  #t1 a  left outer join #temp b
        on a.parent_id = b.id order by a.level asc
    end

    --执行
    如果表organize为层级关系的表,则执行存储过程得到组织关系的树型结果
    sp_get_tree_relation 'orgnaize','org_id','org_name','parent_org',1
  • 相关阅读:
    How does Android, PHP, SQL, JSON, and Remote Databases work together?
    Gson Json
    Protocol Android
    AsyncTask、多线程及线程通信
    线程-Android
    HTTP请求-Android
    Make Your First Android App
    Git版本控制软件结合GitHub从入门到精通常用命令学习手册
    正向代理设置
    vscode 调试 react 项目
  • 原文地址:https://www.cnblogs.com/baishahe/p/1024900.html
Copyright © 2020-2023  润新知