我想创建一个mssql存储过程来运行如下所示的查询:
SELECT thingID
FROM things
WHERE thingParentID = #arguments.id#
递归地,在列表中累积thingID
,然后由存储过程返回。
有没有人知道他们可以链接的这样一个例子?或者一些可能对我有帮助的文件?
感谢。
答案 0 :(得分:7)
这适用于SQL Server 2005及更高版本。
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