【问题标题】:creating a stored procedure from a recursive query从递归查询创建存储过程
【发布时间】:2011-06-17 22:45:54
【问题描述】:

我想创建一个 mssql 存储过程来运行如下查询:

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

递归地在一个列表中累积thingIDs,然后由存储过程返回。

有谁知道可以链接到这样的示例吗?或一些可能对我有帮助的文档?

谢谢。

【问题讨论】:

  • 我认为您不需要为此创建程序。您只需要看看 Recursive CTE
  • rtce 非常感谢您提到这一点!

标签: sql sql-server sql-server-2005 stored-procedures


【解决方案1】:

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

【讨论】:

  • 谢谢!如果有人有机会帮助我弄清楚如何提供多个thingIDs,那也很有帮助。
猜你喜欢
  • 2018-11-09
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 2013-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多