您现在的位置是:网站首页> 编程资料编程资料
SQL SERVER 2008 CTE生成结点的FullPath_mssql2008_
2023-05-27
433人已围观
简介 SQL SERVER 2008 CTE生成结点的FullPath_mssql2008_
好的,现在来看如何生成FullPath:
DECLARE @tbl TABLE
(
Id int
,ParentId int
)
INSERT INTO @tbl
( Id, ParentId )
VALUES ( 0, NULL )
, ( 8, 0 )
, ( 12, 8 )
, ( 16, 12 )
, ( 17, 16 )
, ( 18, 17 )
, ( 19, 17 )
WITH abcd
AS (
-- anchor
SELECT id
,ParentID
,CAST(id AS VARCHAR(100)) AS [Path]
FROM @tbl
WHERE ParentId IS NULL
UNION ALL
--recursive member
SELECT t.id
,t.ParentID
,CAST(a.[Path] + ',' + CAST( t.ID AS VARCHAR(100)) AS varchar(100)) AS [Path]
FROM @tbl AS t
JOIN abcd AS a ON t.ParentId = a.id
)
SELECT Id ,ParentID ,[Path]
FROM abcd
WHERE Id NOT IN ( SELECT ParentId
FROM @tbl
WHERE ParentId IS NOT NULL )
返回:
Id ParentID Path
----------- ----------- ----------------------
18 17 0,8,12,16,17,18
19 17 0,8,12,16,17,19
就这么简单,实际上有Sql server 2008中HierarchyType 也能很好的解决这个问题。我将在后面写一些关于HierarchyType的Post.
希望这篇POST对您有帮助。
Author Peter Liu
复制代码 代码如下:
DECLARE @tbl TABLE
(
Id int
,ParentId int
)
INSERT INTO @tbl
( Id, ParentId )
VALUES ( 0, NULL )
, ( 8, 0 )
, ( 12, 8 )
, ( 16, 12 )
, ( 17, 16 )
, ( 18, 17 )
, ( 19, 17 )
WITH abcd
AS (
-- anchor
SELECT id
,ParentID
,CAST(id AS VARCHAR(100)) AS [Path]
FROM @tbl
WHERE ParentId IS NULL
UNION ALL
--recursive member
SELECT t.id
,t.ParentID
,CAST(a.[Path] + ',' + CAST( t.ID AS VARCHAR(100)) AS varchar(100)) AS [Path]
FROM @tbl AS t
JOIN abcd AS a ON t.ParentId = a.id
)
SELECT Id ,ParentID ,[Path]
FROM abcd
WHERE Id NOT IN ( SELECT ParentId
FROM @tbl
WHERE ParentId IS NOT NULL )
返回:
Id ParentID Path
----------- ----------- ----------------------
18 17 0,8,12,16,17,18
19 17 0,8,12,16,17,19
就这么简单,实际上有Sql server 2008中HierarchyType 也能很好的解决这个问题。我将在后面写一些关于HierarchyType的Post.
希望这篇POST对您有帮助。
Author Peter Liu
您可能感兴趣的文章:
相关内容
- SQLSERVER2008中CTE的Split与CLR的性能比较_mssql2008_
- SQL Server2008中删除重复记录的方法分享_mssql2008_
- SQL Server2008 数据库误删除数据的恢复方法分享_mssql2008_
- SQL Server 2008中的代码安全(八)透明加密(TDE)_mssql2008_
- SQLServer 2008中的代码安全(七) 证书加密_mssql2008_
- SQL Server 2008中的代码安全(六) 对称密钥加密_mssql2008_
- SQLServer 2008中的代码安全(五) 非对称密钥加密_mssql2008_
- SQLServer 2008中的代码安全(四) 主密钥_mssql2008_
- SQL Server 2008中的代码安全(三) 通过PassPhrase加密_mssql2008_
- SQL Server 2008中的代码安全(二) DDL触发器与登录触发器_mssql2008_
