sql server 递归简单应用 下

今天看到这么一道题目:

现有表test_a,有字段col_a,col_b,其值如下
a1    a4
a1    a3
a4    a2
a3    a6
a4    a1
a4    a8
a10   a5
a5    a9
需要得到结果
a1,a3,a4,a2,a6,a8为一集合
a5,a9,a10为一集合
意思就是找出col_a与其相联系的其它列作为一个集合,集合之间没有交集

看到这个题目我的思路是:

  1. 找到表中col_a 列中的第一个元素 a1  得到它的子项 (递归得到所有的子项)  输出出去

  2.找到表中col_a 列中的第二个元素 a1 发现 a1 曾经输出过,不操作它

  3.找到表中col_a 列中的第三个元素 a4 发现 a4 曾经输出过,不操作它

  ··················

  n.找到表中col_a 列中的第N个元素 a10 发现 a10 没有被输出过,那么得到它的子项   (递归得到所有的子项)  输出出去

  ··················

  不断的找不断的输出,最后就会出现想要的结果。

下面是代码:

建表:

create table test_a
(
col_a varchar(10),
col_b varchar(10)
)

插入数据:

insert into test_a 
select 'a1','a4' union all
select 'a1','a3' union all
select 'a4','a2' union all
select 'a3','a6' union all
select 'a4','a1' union all
select 'a4','a8' union all
select 'a10','a5' union all
select 'a5','a9' union all
select 'a22','a33' 

我的代码:

declare    @Index int 
declare    @RowCount int
declare    @RowCount2 int
declare    @ShowStr varchar(1000)--用于存放显示的字符串
declare @t table([id] int identity(1,1) not null,col_a varchar(10))--表变量 用于存放 表test_a中的信息
declare @t2 table([id] int identity(1,1) not null,col_a varchar(10),col_b varchar(10))
declare @t3 table([id] int identity(1,1) not null,col_a varchar(10),col_b varchar(10))
declare @col_a varchar(10)
select @Index=1,@RowCount=0--初始化值
insert into @t
select col_a from test_a--将test_a中的值 存入表变量t中
select @RowCount =count(1) from @t
while @index<=@RowCount--循环条件
begin
    set @ShowStr=''--让显示的字符串为空
    select @col_a=col_a from @t where id=@Index--得到值
    select @RowCount2=COUNT(1) from @t2 where col_a= @col_a or  col_b= @col_a--判断这个得到的值,是否曾经遍历过
    if(@RowCount2=0)--如果没有遍历过开始下面的递归
    begin
        with t_cte(col_a,col_b)--递归得到所需要的信息
        as
        (
            select col_a,col_b from test_a where col_a=@col_a
            union all
            select a.col_a,a.col_b from test_a  a
            inner join t_cte b on a.col_a=b.col_b 
            where  a.col_b!=b.col_a
        )
        
        insert into @t3
        select col_a,col_b from t_cte--将查询出来的值追加的表3中
        
        select @ShowStr=@ShowStr+col_a+',' from (
        select col_a as col_a from @t3
        union
        select col_b as a from @t3)aa
        
        select @ShowStr--输出值
        
        insert into @t2
        select col_a,col_b from @t3--将查出来的值追加到表2中
        
        delete from @t3--清空表3的数据
        
    end    
    set @index=@index+1--循环参数加一
end

 运行之后的结果:

原文地址:https://www.cnblogs.com/haowuji/p/2987175.html