sql server 2005中的递归函数?

时间:2009-11-10 16:45:55

标签: sql-server sql-server-2005 recursive-query

有人可以建议用于说明递归函数的编程示例吗? 例如斐波那契系列或因子..

3 个答案:

答案 0 :(得分:3)

搜索“公用表表达式”。另请参阅this link

更新从上面提到的链接中添加示例:

;WITH Fibonacci(n, f, f1)
AS (
        -- This is the anchor part
        -- Initialize level to 1 and set the first two values as per definition
        SELECT  CAST(1 AS BIGINT),
                CAST(0 AS BIGINT),
                CAST(1 AS BIGINT)

        UNION ALL

        -- This is the recursive part
        -- Calculate the next Fibonacci value using the previous two values
        -- Shift column (place) for the sum in order to accomodate the previous
        -- value too because next iteration need them both
        SELECT  n + 1,
                f + f1,
                f
        FROM    Fibonacci
        -- Stop at iteration 93 because we than have reached maximum limit
        -- for BIGINT in Microsoft SQL Server
        WHERE   n < 93
)
-- Now the easy presentation part
SELECT  n,
        f AS Number
FROM    Fibonacci

答案 1 :(得分:2)

答案 2 :(得分:1)

对于CTE查询递归,请参阅此链接。 http://www.4guysfromrolla.com/webtech/071906-1.shtml

对于TSQL过程/函数递归,请参阅此链接http://msdn.microsoft.com/en-us/library/aa175801%28SQL.80%29.aspx