2009-04-17

Factorial in SQL Server 2005

Just for laughs, here is factorial calculation in SQL Server 2005:

with factorial as (
  select 0 as "n", CAST(1 AS DECIMAL(38)) as "n!"
  union all
  select "n" + 1, "n!" * ("n" + 1) from factorial
)
select top 34 * from factorial

Maximal recursive depth can be achieved using the MAXRECURSION option:

with maximal as (
  select 0 as n
  union all
  select n + 1 from maximal
)
select top 32768 * from maximal
option (maxrecursion 32767)