First, create a CTE with nums, cur, and factorial. Then select the num, 1 as cur and 1 as factorial.
Next you will union this with nums, cur + 1, and factorial * (cur + 1), which would give you the next level. You have to join the CTE and the nums table and on your join (or where) you want to specify that cur + 1 must be <= nums.
Finally, select nums and the MAX of the factorial column from the CTE, grouping by and ordering by the nums column.
;WITH FACT_CTE (nums, cur, factorial)
AS
(
SELECT F.nums, 1 [cur], 1 [factorial]
FROM @Fact F
UNION ALL
SELECT F.nums, cur + 1 [cur], FC.factorial * (FC.cur + 1) [factorial]
FROM @Fact F
JOIN FACT_CTE FC ON
F.nums = FC.nums
AND FC.cur + 1 <= F.nums
)
SELECT nums, MAX(factorial)
FROM FACT_CTE
GROUP BY nums
ORDER BY nums
Tags: recursive cte factorial