声明终止。在语句完成之前,最大递归100已用尽

时间:2017-01-25 17:29:24

标签: sql-server recursion

我尝试在SQL Server中进行SQL-1999样式递归

 CREATE TABLE addressparts(
    AddrPartId INTEGER NOT NULL,
    ParentID INTEGER NOT NULL,
    AddrPartTypeId VARCHAR(30),
    Name VARCHAR(30),
    constraint PK_OBJECTS primary key (AddrPartId))

insert into addressparts values (1, 0, 'country','Zimbabwe');
insert into addressparts values (2, 1, 'city','zi');
insert into addressparts values (3, 2, 'subcity','kalkli');
insert into addressparts values (4, 2, 'subcity','kalkli1');

我想选择递归查询

WITH 
 Rec (AddrPartId, ParentID, AddrPartTypeId, name)
 AS (
   SELECT AddrPartId, ParentID, AddrPartTypeId, name FROM addressparts
   UNION ALL
   SELECT Rec.AddrPartId, Rec.ParentID, rec.AddrPartTypeId, Rec.name
    FROM Rec
    inner join addressparts on Rec.AddrPartId = addressparts.ParentID
   )
 SELECT * FROM Rec 
 WHERE ParentID=0;

但我在标题中有错误

我希望结果为

AddrPartId ParentID
1 0
2 1
3 2
4 2

按级别

1 个答案:

答案 0 :(得分:4)

默认情况下,递归CTE将执行100次递归。

在cte末尾添加选项max recursion以增加默认递归。但是在您的查询中也存在逻辑错误。如果没有错,你正在寻找类似的东西

;WITH Rec (AddrPartId, ParentID, AddrPartTypeId, NAME)
     AS (SELECT AddrPartId,
                ParentID,
                AddrPartTypeId,
                NAME
         FROM   addressparts
         WHERE  ParentID = 0 -- add the parent id filter here 
         UNION ALL
         SELECT A.AddrPartId,  -- don't select from recursive cte 
                A.ParentID,
                A.AddrPartTypeId,
                A.NAME
         FROM   Rec
                INNER JOIN addressparts A
                        ON Rec.AddrPartId = A.ParentID)
SELECT *
FROM   Rec
OPTION (maxrecursion 0); -- here