出于性能方面的考虑,我只需要删除循环并使用一些联接或其他解决方案来更新#Result表中的数据并获得相同的结果,即可循环返回。
标量函数:
CREATE FUNCTION [MultiplyerScl]
(@a INT, @b INT)
RETURNS INT
AS
BEGIN
DECLARE @i AS INT = 2
DECLARE @Value AS INT
IF (@b % @a = 0)
BEGIN
SET @Value = @b
END
ELSE
BEGIN
WHILE (1=1)
BEGIN
IF((@b * @i) % @a = 0)
BEGIN
SET @Value = @b * @i
BREAK;
END
ELSE
BEGIN
SET @i = @i + 1
END
END
END
RETURN @Value
END
表设计及其价值。
CREATE TABLE #NUM (Groupid INT, GroupValue INT)
INSERT INTO #NUM
VALUES (1, 8), (1, 9), (1, 23), (2, 5), (2, 5), (2, 10)
主要用于循环逻辑。
SELECT
Groupid,
GroupValue,
MaxValue = MAX(GroupValue) OVER (PARTITION BY Groupid),
MaxCount = COUNT(1) OVER(),
RID = ROW_NUMBER() OVER (ORDER BY groupid)
INTO
#Result
FROM
#NUM
DECLARE @i AS INT = 1
DECLARE @RawCnt AS INT = (SELECT MAX(MaxCount) FROM #Result)
DECLARE @iGroupid INT
DECLARE @iGroupvalue INT
DECLARE @iMaxValue INT
WHILE(@i <= @RawCnt)
BEGIN
SELECT
@iGroupid = Groupid,
@iGroupvalue = Groupvalue,
@iMaxValue = MaxValue
FROM
#Result
WHERE
RID = @i
UPDATE #Result
SET MaxValue = dbo.[MultiplyerScl](@iGroupvalue, @iMaxValue)
WHERE Groupid = @iGroupid
SET @i = @i + 1
END
SELECT * FROM #Result