SQL在存储过程中使用递归

来源:互联网 发布:sql union all用法 编辑:程序博客网 时间:2024/04/28 23:21
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

递归的基本概念非常简单:一段给定的代码对自身进行调用,直到某些边界条件得到满足。在本文中,我们将演示如何在T-SQL中使用递归

在我的眼中,递归是最为精致的程序结构之一。我已经在许多场合用不同的编程语言实现过它。递归的基本概念非常简单:一段给定的代码对自身进行调用,直到某些边界条件得到满足。我将通过下面的内容展示如何在T-SQL中使用递归。我所用到的是递归的经典例子:阶乘计算。

阶乘的意思就是将小于等于这一数字的所有数字相乘,直至乘到2。例如,factorial(10)即等于10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2(你也可以加上“*1”,但似乎是多此一举)。

以下代码即实现了阶乘:

CREATE PROCEDURE [dbo].[Factorial_ap]

(

    @Number Integer,

    @RetVal Integer OUTPUT

)

AS

    DECLARE @In Integer

    DECLARE @Out Integer

   IF @Number!= 1

       BEGIN

       SELECT @In = @Number – 1

        EXECFactorial_ap @In, @Out OUTPUT

       SELECT @RetVal = @Number * @Out

    END

        ELSE

           BEGIN

               SELECT @RetVal = 1

           END

RETURN

GO<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击