是否想找到一个数字的阶乘之和?
但是我需要像5这样的结果之和!是120 在这个我想要1 + 2 + 0 = 3
答案 0 :(得分:1)
这可以通过递归CTE来实现:
--here you decide what factorial to calculate
declare @i int = 5;
;with cte as(
select 1 n, 1 factorial
union all
select n + 1, factorial * (n + 1) from cte
where n < @i
)
select factorial,
--just to make sure we correctly sum all digits
(factorial%100000)/10000 +
(factorial%10000)/1000 +
(factorial%1000)/100 +
(factorial%100)/10 +
factorial%10 DigitsSum
from cte
where n = @i
答案 1 :(得分:0)
您可以使用如下代码:
declare @a int
set @a = 120
declare @temp varchar(20)
set @temp = cast(@a as varchar(20))
declare @Result int
set @Result = 0
declare @tempLength int
set @tempLength = DATALENGTH(@temp)
while @tempLength > 0
begin
set @Result = @Result + cast(SUBSTRING(@temp, @tempLength, 1) as int)
set @tempLength = @tempLength - 1
end
select @Result
变量“ a”与您的阶乘结果相同。
答案 2 :(得分:-1)
尝试使用substring()函数并分离数字,然后将所有数字加在一起。
答案 3 :(得分:-1)
您可以从sum of factorial of the no创建函数以找出数字的阶乘。 然后使用以下查询找到总和:
DECLARE @var1 int
select @var1 = dbo.Factorial(5)
;WITH i AS (
SELECT @var1 / 10 n, @var1 % 10 d
UNION ALL
SELECT n / 10, n % 10
FROM i
WHERE n > 0
)
SELECT SUM(d)
FROM i;