A Recursion : Recursive function « Store Procedure Function « SQL Server / T-SQL






A Recursion

 


6>    CREATE PROC spFactorial
7>    @ValueIn int,
8>    @ValueOut int OUTPUT
9>    AS
10>    DECLARE @InWorking int
11>    DECLARE @OutWorking int
12>    IF @ValueIn != 1
13>    BEGIN
14>          SELECT @InWorking = @ValueIn - 1
15>
16>          EXEC spFactorial @InWorking, @Outworking OUTPUT
17>
18>          SELECT @ValueOut = @ValueIn * @OutWorking
19>    END
20>    ELSE
21>    BEGIN
22>          SELECT  @ValueOut = 1
23>    END
24>    RETURN
25>    GO
1>
2>
3>    DECLARE @WorkingOut int
4>    DECLARE @WorkingIn int
5>    SELECT @WorkingIn = 5
6>    EXEC spFactorial @WorkingIn, @WorkingOut OUTPUT
7>
8>    PRINT CAST(@WorkingIn AS varchar) + ' factorial is ' + CAST(@WorkingOut AS varchar)
9>    GO
5 factorial is 120
1>
2>    drop PROC spFactorial;
3>GO

 








Related examples in the same category