SQL编写存储过程计计算1!+2!+3!+…+N!

2025-04-05 13:05:38
推荐回答(2个)
回答1:

create procedure sp_getval @n int
as
declare @i int,@j int,@val int,@sval int
set @i=1
set @val=0
while @i<=@n
begin
set @j=@i
set @sval=1
while @j>1
begin
set @sval=@sval*@j
set @j=@j-1
end
set @val=@val+@sval
set @i=@i+1
end
return @val

go

不过这类东西在程序中计算要比在数据库中快的多。

回答2:

drop procedure p_test
go
CREATE procedure p_test(@n int)
as
begin
declare @i int -- 外层循环变量
declare @j int -- 内层循环变量
declare @c varchar(2000) -- 结果字符串
declare @totalc varchar(2000) --内层循环拼接字符串
select @i=1
select @j=1
select @c = ''
if @n =0
begin
select '1' as [0!]
end
else
while @i<=@n
begin
select @j=@i
select @totalc = convert(char,@j)
while @j<>1
begin
select @totalc = rtrim(@totalc)+'*'+convert(char,(@j-1))
select @j=@j-1
end
select @c=rtrim(@c)+'+'+rtrim(@totalc)
select @i = @i+1
end
select @c='select '+substring(@c,2,len(@c))
execute(@c)
end