如何在SQL中执行递归除法?
我知道基本前提是
declare @i = 0
declare @testValue bigint = FLOOR(@num/@dem)
while @testValue>0
begin
set @num = @num - @testValue*@dem
set @testValue = FLOOR(@num/@dem)
set @i = @i + 1
end
,但我不知道如何以有效的方式做到这一点。
答案 0 :(得分:0)
您的查询可以重写如下:
Declare @Num BigInt = 10000,
@Dem BigInt = 50
;With Cte As
(
Select Floor(@num / @dem) TestValue, 1 As Iteration
Union All
Select Floor((TestValue * @Dem) / @Dem) As TestValue, Iteration + 1
From Cte
Where TestValue > 0
)
Select *
From Cte
但是它的设计存在问题。它将值乘以分割结果,再次分割,产生无限循环。
我相信这就是你想要做的事情:
Declare @Num BigInt = 10000,
@Dem BigInt = 50
;With Cte As
(
Select Floor(@num / @dem) TestValue, 1 As Iteration
Union All
Select Floor(TestValue / @Dem) As TestValue, Iteration + 1
From Cte
Where TestValue > 0
)
Select *
From Cte
在这种情况下,给出以下结果:
TestValue Iteration
200 1
4 2
0 3