存储过程中使用递归
阶乘的意思就是将小于等于这一数字的所有数字相乘,直至乘到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
??????? EXEC Factorial_ap @In, @Out OUTPUT
??????? SELECT @RetVal = @Number * @Out
??? END
??????? ELSE
??????????? BEGIN
??????????????? SELECT @RetVal = 1
??????????? END
RETURN
GO