sql数据库存在父级、子级联用的递归,具体代码如下:
----------------------------------------------------------------------------
--sql 数据库递归---在数据库存在级联用到,例如商品的父类和子类之间所属关系
----------------------------------------------------------------------------
WITH T AS ( SELECT
* ,
lv = 0 ,
struct = CAST(id AS NVARCHAR) --struct 获取的数据包含它本身和它的上级节点
FROM
tb_accounttype
WHERE
pid = 0
UNION ALL
SELECT
a.* ,
lv = ( b.lv + 1 ) ,
struct = CAST(CAST(b.struct AS NVARCHAR) + ','
+ CAST(a.id AS NVARCHAR) AS NVARCHAR)
FROM
tb_accounttype a
JOIN T b ON a.pid = b.AccountTypeNo
)
SELECT
*
FROM T
-- 如果需要加入条件查询例如查询name等于你需要查询的数据则加入一下代码即可
-- where T.name LIKE '%00%'
OPTION
( MAXRECURSION 0 )
更多信息请查看IT技术专栏