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 thingID
s 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
精彩评论