This is one little stored procedure to get the factorial of a given number. Some of this little things make you very good in programming as you develop your logic building skills across different areas of computing. One important and good thing about programming is that, once you know the logic in accomplishing a task, its very easy to accomplish that task in different languages. So the first thing to accomplish in programming is logic building. It helps a lot writing pseudo code for a task and dry running this code to see if you get the required output before even translating this pseudo code to a specific language. This makes a lot of difference when it comes to programming and should be the first thing to develop to really have a pleasurable programming career. So, l was about to jump to bed and l decide to just write something before l sleep so l wrote this short procedure to put me to bed.

CREATE PROCEDURE Factorial (@num INT) AS
BEGIN

DECLARE @fact bigint
SET @fact = 1
IF(@num = 0)
BEGIN
SET  @fact = 1
END
ELSE
BEGIN
WHILE(@num >0)
BEGIN
SET @fact = @fact * @num
SET @num = @num -1
END
END
RETURN @fact
END

 

We can execute like this

Declare @FactValue int
exec @FactValue = Factorial 5
print @FactValue

That’s all. Jah bless

 

1 thought on “TSQL Stored procedure to get factorial of a given number

  1. 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)
    INTO dbo.Factorial
    FROM sys.all_columns
    ;
    –===== 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.
    UPDATE f
    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *