使用while循环重写递归CTE

时间:2018-01-16 07:30:30

标签: sql sql-server sql-server-2008 sql-server-2012 sql-server-2008-r2

我想在SQL Server中将Recursive CTE重写为while循环。

我该如何重写?示例查询如下所示。

WITH CTE
 AS (
 SELECT DISTINCT
        ID,
        [NAME],
        ID AS PARENTID,
        ITEMTYPE,
        COST
 FROM TABLE1
 UNION ALL
 SELECT T.ID,
        C.[NAME],
        C.ID AS PARENTID,
        T.ITEMTYPE,
        T.COST
 FROM CTE AS C
      INNER JOIN TABLE1 T ON C.ID = T.ID
 WHERE C.ITEMTYPE <> 'individual')
 SELECT *
 FROM CTE;

2 个答案:

答案 0 :(得分:2)

重写非常简单。

DECLARE @LoopCount INT = 0;

 SELECT DISTINCT
        ID,
        [NAME],
        ID AS PARENTID,
        ITEMTYPE,
        COST
 INTO #CTE
 FROM TABLE1

 WHILE @@ROWCOUNT > 0 AND @LoopCount < 100
 BEGIN
 INSERT INTO #CTE
  SELECT T.ID,
        C.[NAME],
        C.ID AS PARENTID,
        T.ITEMTYPE,
        T.COST
 FROM #CTE AS C
      INNER JOIN TABLE1 T ON C.ID = T.ID
 WHERE C.ITEMTYPE <> 'individual';

 SET @LoopCount += 1;

 END;

 IF @LoopCount = 100
    THROW 50000, 'Max recursion limit exceeded', 0

 SELECT *
 FROM #CTE

答案 1 :(得分:0)

你需要这样的东西。不太确定为什么你需要循环。

List<MyEntity> findByQp1OrQp2OrQp3(@Nullable String qp1, @Nullable Long qp2, @Nullable String qp3);

SELECT * FROM #tempFinal