开发者

creating a stored procedure from a recursive query

I'd like to create a mssql stored procedure to run a query like the fo开发者_如何学Gollowing:

SELECT thingID FROM things WHERE thingParentID = #arguments.id#

recursively, accumulating thingIDs in a list which is then returned by the stored procedure.

Does anyone know of a example like this that they can link to? or some documentation that might help me?

Thanks.


This will work on SQL Server 2005 and up.

CREATE FUNCTION dbo.Ancestors (@thingID int)
RETURNS TABLE
AS
RETURN
    WITH CTE AS
    (
        SELECT thingID, 1 [Level]
        FROM dbo.things
        WHERE thingParentID = @thingID

        UNION ALL

        SELECT p.thingID, [Level] + 1 [Level]
        FROM CTE c
        JOIN dbo.things p
            ON p.thingParentID = c.thingID
    )
    SELECT thingID, [Level]
    FROM CTE

GO

CREATE PROCEDURE GetAncestors (@thingID int)
AS
    SELECT thingID, [Level]
    FROM dbo.Ancestors(@thingID)
GO
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜