Calculate the factorial of 5

An important mathematical operation is calculating the factorial of a positive integer n. The factorial of n is defined by the product of all positive integers less than or equal to n. For example, the factorial of 3 (denoted by n!) is defined as:

3! = 1 x 2 x 3 = 6

To calculate the factorial of n, many different solutions exist. In this exercise, you will determine the factorial of 5 iteratively with SQL. You can use DECLARE @local_variable to define variables in SQL Server.

Recall the syntax of a WHILE loop is:

WHILE condition
BEGIN
   {...statements...}
END;

This is a part of the course

“Hierarchical and Recursive Queries in SQL Server”

View Course

Exercise instructions

  • Set the @target factorial, which will also serve as the termination condition, to 5.
  • Initialize the @factorial result.
  • Calculate the @factorial number by taking the product of the factorial result so far and the current iteration.
  • Reduce the termination condition by 1 at the end of the iteration.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

-- Define the target factorial number
DECLARE @target float = ___
-- Initialization of the factorial result
DECLARE @factorial float = ___

WHILE @target > 0 
BEGIN
	-- Calculate the factorial number
	SET @factorial = @___ * @___
	-- Reduce the termination condition  
	SET @target = @___ - 1
END

SELECT @factorial;