zoukankan      html  css  js  c++  java
  • sqlserver中递归写法

    递归分两种:一种由父项向下级递归,另一种是由子项向上级递归。下面就这两种情况做个简单的处理。

    假设有一个表treeview,包含字段 id,parentid,text 分别代表id,上级id,描述字段(这里就不把建表sql写出来了)。

    1、由父项递归下级

    with cte(id,parentid,text) 
    as 
    (--父项 
    select id,parentid,text from treeview where parentid = 450 --需替换成自己希望查询的id
    union all 
    --递归结果集中的下级 
    select t.id,t.parentid,t.text from treeview as t 
    inner join cte as c on t.parentid = c.id 
    ) 
    select id,parentid,text from cte
    

    2、由子级递归父项 

    with cte(id,parentid,text) 
    as 
    (--下级父项 
    select id,parentid,text from treeview where id = 450 --需替换成自己希望查询的id
    union all 
    --递归结果集中的父项 
    select t.id,t.parentid,t.text from treeview as t 
    inner join cte as c on t.id = c.parentid 
    ) 
    select id,parentid,text from cte
    

     简单的例子。 

      

  • 相关阅读:
    MySQL的语句执行顺序
    mysql 基本使用
    spring 事务详解
    java 设计模式
    hibernate 简单查询
    qwq(一些有趣的数学题)
    关于libra9z
    HDU6756 Finding a MEX
    CF1386C Joker
    CF1340F Nastya and CBS
  • 原文地址:https://www.cnblogs.com/iceriver315/p/9704800.html
Copyright © 2011-2022 走看看