SQL:如何从递归查询创建视图?

Posted

技术标签:

【中文标题】SQL:如何从递归查询创建视图?【英文标题】:SQL: How to create view from a recursive query? 【发布时间】:2011-04-25 23:17:38 【问题描述】:

问题:我想从递归查询中得出一个视图。

查询与此处的查询具有相同的结构: http://forums.asp.net/t/1207101.aspx

并将树视图表示为有序数据集。

如何创建执行此操作的视图:

;WITH Tree (ID, [NAME], PARENT_ID, Depth, Sort) AS
(
    SELECT ID, [NAME], PARENT_ID, 0 AS Depth, CONVERT(varchar(255), [Name]) AS Sort FROM Category
    WHERE PARENT_ID = 0
    UNION ALL
    SELECT CT.ID, CT.[NAME], CT.PARENT_ID, Parent.Depth + 1 AS Depth, 
    CONVERT(varchar(255), Parent.Sort + ' | ' + CT.[NAME]) AS Sort
    FROM Category CT
    INNER JOIN Tree as Parent ON Parent.ID = CT.PARENT_ID
)

-- HERE IS YOUR TREE, Depths gives you the level starting with 0 and Sort is the Name based path
SELECT ID, [NAME], PARENT_ID, Depth, Sort FROM Tree
ORDER BY Sort

【问题讨论】:

您最好创建一个执行此操作的内联表值函数。然后你可以参数化你传递给它的 Parent_Id。 最好在视图中进行,并且可能将主根 uid 添加为列,并从存储过程中查询该视图。当你有很多数据时,表值函数会变得很慢,因为它们会在内存中创建临时表,如果内存不足,它们会被交换。 【参考方案1】:

应该很简单:

CREATE VIEW YourViewName
AS
    WITH Tree (ID, [NAME], PARENT_ID, Depth, Sort) AS
    (
        SELECT ID, [NAME], PARENT_ID, 0 AS Depth, CONVERT(varchar(255), [Name]) AS Sort         
        FROM Category
        WHERE PARENT_ID = 0
        UNION ALL
        SELECT CT.ID, CT.[NAME], CT.PARENT_ID, Parent.Depth + 1 AS Depth, 
        CONVERT(varchar(255), Parent.Sort + ' | ' + CT.[NAME]) AS Sort
        FROM Category CT
        INNER JOIN Tree as Parent ON Parent.ID = CT.PARENT_ID
    )

    -- HERE IS YOUR TREE, Depths gives you the level starting with 0 and Sort is the Name based path
    SELECT ID, [NAME], PARENT_ID, Depth, Sort FROM Tree
GO

【讨论】:

啊,分号,抱歉没看到。 PS:不,不是那么简单,只是几乎:您需要删除 order by 或将前 100% 添加到 select 语句中;-) 您需要删除 ORDER BY - 它不属于视图,SQL 无论如何都会拒绝它 @Quandary, @Damien:感谢ORDER BY 的关注。剪切-粘贴编码的危害之一! :-) 我会适当更新。

以上是关于SQL:如何从递归查询创建视图?的主要内容,如果未能解决你的问题,请参考以下文章

sql递归cte在视图中不能正常工作

ms sql 2005 递归查询如何实现

sql 怎么递归查询的方法:

sql server 递归查询

SQL递归查询所有子节点

sql 递归查询