1. Learn
  2. /
  3. Courses
  4. /
  5. Hierarchical and Recursive Queries in SQL Server

Exercise

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;

Instructions

100 XP
  • 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.