-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathfactorial.sql
More file actions
69 lines (58 loc) · 1.33 KB
/
factorial.sql
File metadata and controls
69 lines (58 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
if object_id('dbo.factorial', 'FN') is not null
drop function dbo.factorial;
go
create function dbo.factorial(@n numeric(38, 0))
/* Описание: Функция вычисляет факториал
от заданного числа.
Справка: факториал числа 5 это 1 * 2 * 3 * 4 * 5
Пример: select dbo.factorial(7)
Ограничение: максимальное заданное число = 33
*/
returns numeric(38, 0)
as begin
declare
@result numeric(38, 0),
@i numeric(38, 0);
select
@i = 1,
@result = 1;
while @i !> @n begin
select
@result *= @i,
@i += 1;
end;
return @result
end;
go
-----------------------------------------------------------
if object_id('dbo.factorial', 'FN') is not null
drop function dbo.factorial;
go
create function dbo.factorial(@n int)
/* Описание: Функция вычисляет факториал Рекурсивно
от заданного числа.
Справка: факториал числа 5 это 1 * 2 * 3 * 4 * 5
Пример: select dbo.factorial(7)
*/
returns int
as begin
declare @result int;
with
_f(n, r) as (
select 1, 1
union all
select
n + 1
,r * (n + 1)
from _f
where n !> 6
)
,f as (
select r
from _f
where n = @n
)
select @result = r from f;
return @result
end;
go