如何限制递归CTE行数

时间:2014-06-14 03:14:35

标签: sql recursion common-table-expression

我有一个函数用来生成记录id,我想用CTE来获取批量记录id。 现在递归CTE如下

  with T as (
    select 
        dbo.Ufn_GetRecordId() AS recordId
    union all
    SELECT
        dbo.Ufn_GetRecordId() AS recordId
    FROM T

)select * from T
OPTION (MaxRecursion 0);

但是,此查询不会终止。如何限制CTE的数量?(例如,如果我在T中只需要3行)

2 个答案:

答案 0 :(得分:2)

您可以尝试以下内容。取自SQL Server: How to limit CTE recursion to rows just recursivly added?

的想法
with T as (
    select 
        dbo.Ufn_GetRecordId() AS recordId, 1 as testnum
    union all
    SELECT
        dbo.Ufn_GetRecordId() AS recordId, testnum + 1
    FROM T
    WHERE testnum < 3

)select * from T
OPTION (MaxRecursion 0);

这将限制为3个返回的行。

答案 1 :(得分:1)

这是一种使用递归CTE生成N行的相当标准的方法。

WITH T 
     AS (SELECT 1 AS Dummy 
         UNION ALL 
         SELECT Dummy + 1 
         FROM   T 
         WHERE  Dummy < 3) 
SELECT dbo.Ufn_GetRecordId() AS RecordId 
FROM   T; 

如果您需要生成超过100个数字,那么您需要OPTION (MAXRECURSION 0)(或某个合适的值而不是0)。