如何在SQL中存储递归CTE的结果?

时间:2018-04-12 10:41:32

标签: sql sql-server common-table-expression recursive-query

如果我有这样的递归CTE,我如何将结果存储在变量中?

protoc [other-options] some.proto

我已尝试过以下内容,但SSMS抱怨两个选项中的语法:

WITH MyCTE (ChildID, ParentID)
AS
(
   SELECT ID, ParentID From MyTable
    WHERE ID = 1
   UNION ALL
    SELECT MT.ID, MT.ParentID 
    FROM MyCTE Child
    JOIN MyTable MT ON MT.ID = Child.ParentID
    WHERE Child.ParentID IS NOT NULL
)
SELECT COUNT(*)
FROM MyCTE
OPTION (MAXRECURSION 20)

DECLARE @numberOfRecords int = (
WITH MyCTE (ChildID, ParentID)
AS
(
   SELECT ID, ParentID From MyTable
    WHERE ID = 1
   UNION ALL
    SELECT MT.ID, MT.ParentID 
    FROM MyCTE Child
    JOIN MyTable MT ON MT.ID = Child.ParentID
    WHERE Child.ParentID IS NOT NULL
)
SELECT COUNT(*)
FROM MyCTE
OPTION (MAXRECURSION 20))

1 个答案:

答案 0 :(得分:4)

您可以先声明变量然后再分配它:

DECLARE @numberOfRecords int;

WITH MyCTE (ChildID, ParentID) AS (
      SELECT ID, ParentID
      FROM MyTable
      WHERE ID = 1
      UNION ALL
      SELECT MT.ID, MT.ParentID 
      FROM MyCTE Child JOIN
           MyTable MT
           ON MT.ID = Child.ParentID
      WHERE Child.ParentID IS NOT NULL
     )
SELECT @numberOfRecords = COUNT(*)
FROM MyCTE
OPTION (MAXRECURSION 20);