Not quite true. That stored procedure is limited to a factorial of only 12 because of the INT datatype. Because it's a proc, it's difficult to use in a non-RBAR environment. And I'm not sure that I'd trust anyone's code that blatantly had an unused variable in it. 😉
I guess I don't understand why people insist on recalculating that which will not change. For example, no matter how many times you calculate it, 170! will always return the same number. So why not calculate it just once and store it in a "helper" table?
Here's how to make a Factorial "helper" table.
--===== Create the table with columns for N and N!.
-- This will prepopulate the values of N, as well.
SELECT TOP 171
N = IDENTITY(INT,0,1),
[N!] = CAST(0 AS FLOAT)
--===== Add the quintessential PK for max performance of future lookups
ALTER TABLE dbo.Factorial
ADD CONSTRAINT PK_Factorial
PRIMARY KEY CLUSTERED (N) WITH FILLFACTOR = 100
--===== Declare a variable that well need to keep track of the previous product.
DECLARE @Factorial FLOAT;
--===== Update the table with factorials.
SET @Factorial = [N!] = CASE WHEN N > 0 THEN @Factorial * N ELSE 1 END
FROM dbo.Factorial f WITH (TABLOCKX, INDEX(1))
OPTION (MAXDOP 1)
--===== Show our work
SELECT * FROM dbo.Factorial ORDER BY N;
Then all you have to do is join to the factorial table for any number of rows in a set based fashion instead of recalculating the same thing over and over.
is pronounced "ree-bar
" and is a "Modenism
" for R
First step towards the paradigm shift of writing Set Based code:
________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.
"Change is inevitable... change for the better is not".
"Dear Lord... I'm a DBA so please give me patience because, if you give me strength, I'm going to need bail money too!"
How to post code problems
How to Post Performance Problems
Create a Tally Function (fnTally)