views:

51

answers:

1

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
+5  A: 

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
Joe Stefanelli
Argh, the semicolon, sorry don't saw it. PS: No it's not that simple, only almost: You need to remove order by or add top 100 percent to the select statement ;-)
Quandary
You'll want to remove that ORDER BY - It doesn't belong in a view, and SQL will reject it anyway
Damien_The_Unbeliever
@Quandary, @Damien: Thanks for the catch on the `ORDER BY`. One of the hazards of cut-n-paste coding! :-) I'll update appropriately.
Joe Stefanelli