今天遇到一个问题记录下,我们需要导入其他系统的树形结构数据,但是我们这边的层级是要以 父级.子级.子级 这样的Code 才能实现,而对方给到的数据却是以当前编码和父级编码这样的数据给到我们,所以只能对编码做点改造,话不多说,直接上图,下面为待整理的数据
--对方表结构
CREATE TABLE [dbo].[PARAM_PARAM]
(
[ID] [CHAR](12),
[PARENTID] [CHAR](12),
[CLASSID] [CHAR](5),
[GROUPID] [CHAR](6),
[CODE] [VARCHAR](255),
[NAME] [VARCHAR](255),
[VALID] [CHAR](1),
[DESCRIPTION] [VARCHAR](1000),
[BRIEFNAME] [VARCHAR](255),
[UPDATEDATE] [DATE],
[USERID] [VARCHAR](40),
[DISPLAYORDER] [VARCHAR](255)
);
GO
对方数据插入后的显示效果
分析:只要是树形结构的一般都会有这两个列,一个是当前节点Code 一个是父级节点Code,我们只需要递归去刷一下Code和名称就可以实现,代码如下。
WITH child (CODE, NAME, DISPLAYORDER, PARENTID, level, newCode, newName, parentCode)
AS (
SELECT
CODE,
NAME,
DISPLAYORDER,
PARENTID,
1 AS level,
CONVERT (VARCHAR(100), CODE) AS newCode,
CONVERT (VARCHAR(300), NAME) AS newName,
CODE AS parentCode
FROM PARAM_PARAM
WHERE DISPLAYORDER = '000000021348' --最顶级编码
UNION ALL
SELECT
a.CODE,
a.NAME,
a.DISPLAYORDER,
a.PARENTID,
b.level + 1,
CONVERT (VARCHAR(100), b.newCode + '.' + a.CODE) AS newCode,
CONVERT (VARCHAR(300), b.newName + '-' + a.NAME) AS newName,
b.CODE AS parentCode
FROM dbo.PARAM_PARAM a
INNER JOIN child b ON a.PARENTID = b.DISPLAYORDER
)
SELECT
*
FROM child
ORDER BY child.CODE;
--注意:用with语法,后面执行查询时必须要把当前表查询出来
效果如下
如果表有 IfEnd 字段,那么根据如下代码即可查询出来
WITH child (CODE, NAME, DISPLAYORDER, PARENTID, level, newCode, newName, parentCode, IfEnd)
AS (
SELECT
CODE,
NAME,
DISPLAYORDER,
PARENTID,
1 AS level,
CONVERT (VARCHAR(100), CODE) AS newCode,
CONVERT (VARCHAR(300), NAME) AS newName,
CODE AS parentCode,
0 AS IfEnd
FROM PARAM_PARAM
WHERE DISPLAYORDER = '000000021348' --最顶级编码
UNION ALL
SELECT
a.CODE,
a.NAME,
a.DISPLAYORDER,
a.PARENTID,
b.level + 1,
CONVERT (VARCHAR(100), b.newCode + '.' + a.CODE) AS newCode,
CONVERT (VARCHAR(300), b.newName + '-' + a.NAME) AS newName,
b.CODE AS parentCode,
IfEnd = (CASE
WHEN EXISTS
( SELECT
1
FROM dbo.PARAM_PARAM
WHERE PARENTID = a.DISPLAYORDER) THEN
0
ELSE 1
END)
FROM dbo.PARAM_PARAM a
INNER JOIN child b ON a.PARENTID = b.DISPLAYORDER
)
SELECT
*
FROM child
ORDER BY child.CODE;
SELECT
*
FROM Tree A
WHERE NOT EXISTS
( SELECT
*
FROM Tree B
WHERE A.ParentCode = B.Code);
查询当前所有末级节点
SELECT
*
FROM Tree A
WHERE NOT EXISTS
( SELECT
*
FROM Tree B
WHERE A.Code = B.ParentCode);