如果我有这样的递归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))
答案 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);