snippetsqlModerate
How do I do factorials in SQL Server?
Viewed 0 times
sqlfactorialsserverhow
Problem
In PostgreSQL, I often times want to do something like find the factorial of 7. I can do that very simply with
Even Excel has
How do I do that with SQL Server 2017 Enterprise?
SELECT 7!;
-- PostgreSQL is so full featured
-- it even supports a prefix-factorial
SELECT !!7;Even Excel has
FACT,=FACT(7)How do I do that with SQL Server 2017 Enterprise?
Solution
I am not aware of a built-in function to do this. You need to roll your own. Here is how I do it:
The Math_Factorial function is in the Free version of the SQL# SQLCLR library (that I wrote).
OR
if you do not need it in function / UDF form, then it might be more efficient to do the following:
Both approaches shown above take into account the "special" condition of passing in
For the T-SQL approach, just make
SELECT SQL#.Math_Factorial(5); -- 120The Math_Factorial function is in the Free version of the SQL# SQLCLR library (that I wrote).
OR
if you do not need it in function / UDF form, then it might be more efficient to do the following:
DECLARE @BaseNumber INT = 5,
@Result BIGINT = 1;
;WITH cte AS
(
SELECT TOP (@BaseNumber) ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS [Num]
FROM sys.columns
ORDER BY Num
)
SELECT @Result *= [Num]
FROM cte;
SELECT @Result;
-- 120Both approaches shown above take into account the "special" condition of passing in
0 as the "BaseNumber" and it returning 1 instead of 0.SELECT SQL#.Math_Factorial(0); -- 1For the T-SQL approach, just make
@BaseNumber = 0 and it will return 1 (no need to copy and paste it again here just for that).Code Snippets
SELECT SQL#.Math_Factorial(5); -- 120DECLARE @BaseNumber INT = 5,
@Result BIGINT = 1;
;WITH cte AS
(
SELECT TOP (@BaseNumber) ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS [Num]
FROM sys.columns
ORDER BY Num
)
SELECT @Result *= [Num]
FROM cte;
SELECT @Result;
-- 120SELECT SQL#.Math_Factorial(0); -- 1Context
StackExchange Database Administrators Q#200503, answer score: 16
Revisions (0)
No revisions yet.