2011-06-17 95 views
2

创建存储过程,我想创建一个mssql的存储过程运行类似以下的查询:从递归查询

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

递归,其中然后返回一个列表积累thingID小号由存储过程。

有谁知道这样的例子,他们可以链接到?或一些可能帮助我的文档?

谢谢。

+3

我不认为你需要为此创建一个过程。所有你需要的是看看递归CTE – a1ex07

+0

rtce是甜的感谢提及! – ztatic

回答

6

这将适用于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 
+0

+1 Nice answer .. – CResults

+0

谢谢!如果有人有机会帮我弄清楚如何提供多个'thingID',那么这也会有帮助。 – ztatic