Friday, June 19, 2015

SQL script to find the factorial of a number

We can easily return the factorial of a number by using CTE.

Find below the script to do that:


WITH Fact (N, Fact) AS
(
SELECT 1, 1
UNION ALL
SELECT
(N+1), Fact*(N+1)
FROM
Fact
WHERE N < 5
)

SELECT
N
,Fact
FROM

Fact

Result:

If we see the above script, first it will return 1, 1 and it will loop through the Fact CTE to get the factorial value for the numbers from 2 to 5

Labels: , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home