欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

成语接龙-查找指定层数以内的成语

程序员文章站 2022-06-27 21:54:36
--从一个成语开始接龙找到另一个成语 DECLARE @cb NVARCHAR(4)= '为所欲为'; --, --@ce NVARCHAR(15)= '鸡飞狗跳'; WITH cte_get_path AS ( SELECT word , --0 AS is_recycle , ... ......
--从一个成语开始接龙找到另一个成语
declare @cb nvarchar(4)= '为所欲为'; --,
    --@ce nvarchar(15)= '鸡飞狗跳';
with    cte_get_path
          as ( select   word ,
                        --0 as is_recycle ,
                        cast(word as nvarchar(max)) as cpath ,
                        1 as level ,
                        first_word ,
                        last_word
               from     dbo.cy
               where    word = @cb
               union all
               select   s.word ,
                        --case when s.word = @ce then 1
                        --     else 0
                        --end as is_recycle ,
                        cast(p.cpath + '>' + s.word as nvarchar(max)) as cpath ,
                        p.level + 1 as level ,
                        s.first_word ,
                        s.last_word
               from     dbo.cy as s
                        inner join cte_get_path as p on p.last_word = s.first_word
                                                        and charindex(s.word,
                                                              p.cpath) = 0
                                                        and p.level + 1 <= 5--限制成语的个数为5个
                                                        --and p.is_recycle = 0
             )
    select  *
    from    cte_get_path
    --where   cte_get_path.word = @ce;