简体   繁体   中英

How can I store the result of a recursive CTE in SQL?

If I have a recursive CTE like this, how can I store the result in a variable?

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)

I've tried the following, but SSMS complains about the syntax in both options:

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))

and

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
)
DECLARE @numberOfRecords int = (
SELECT COUNT(*)
FROM MyCTE
OPTION (MAXRECURSION 20))

You can declare the variable first and then assign it:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM