Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to create view from a recursive query?

Question: I have a view which I want to derive from a recursive query.

The query is of the same structure as this one here: http://forums.asp.net/t/1207101.aspx

And represents a treeview as an ordered dataset.

How can I create a view which does this:

;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
like image 887
Stefan Steiger Avatar asked Oct 15 '10 14:10

Stefan Steiger


People also ask

How do I turn a SQL query into a view?

SQL Server CREATE VIEW First, specify the name of the view after the CREATE VIEW keywords. The schema_name is the name of the schema to which the view belongs. Second, specify a SELECT statement ( select_statement ) that defines the view after the AS keyword. The SELECT statement can refer to one or more tables.

What is recursive view in SQL?

Recursion is achieved by WITH statement, in SQL jargon called Common Table Expression (CTE). It allows to name the result and reference it within other queries sometime later.

How do you use recursive CTE?

Recursive CTE's Execution Order The first step is, execute the initial query (anchor member) which returns the base result set which is used for the next iteration. The second step is, execute the recursive query with the input result set from the previous iteration.


1 Answers

It should be as simple as:

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
like image 71
Joe Stefanelli Avatar answered Oct 13 '22 00:10

Joe Stefanelli